1

In my service file:

postDetail: FirebaseObjectObservable<any>;
constructor( private af: AngularFire ) { }
public getBanquetDetail(id){
    this.postDetail = this.af.database.object('/Posts/'+id) as FirebaseObjectObservable<Post>;    
    return this.postDetail;
  }

In my component.ts file

    export class PostDetailComponent implements OnInit {
        id: any;
        test: any;
        constructor(private banquetService: PostService, private router: Router, private route: ActivatedRoute) { }

        ngOnInit() {
            // Get the id
            this.id = this.route.snapshot.params['id'];
            this.banquetService.getBanquetDetail(this.id).subscribe(response => {
console.log(response)                
this.test = response
            })
        }      

    }

I am getting an object in console but couldnt render the value as

<h2>{{test.title}}</h2>

I am getting error as :

TypeError: Cannot read property 'title' of undefined

Anyone please help me? Where am I worng?

2 Answers 2

3

value of test is assigned after the subscription, hence title is not available when loaded.

you can add safe navigation operator (?) like below to evaluate only after it has not null value.

 <h2>{{test?.title}}</h2>

you may read about safe navigation operator here.

Hope this helps!!

Sign up to request clarification or add additional context in comments.

Comments

2

Use the elvis operator (?) when you are not sure if every object in the path exist:

<h2>{{test?.title}}</h2>

In Angular 2, the "Elvis operator" (really, the safe navigation operator) allows an object path to be safely navigated in situations in which you are not entirely sure if every object in the path exists. This prevents null-reference exceptions by returning the result of the path if is valid; or, null otherwise. - Ben Nadel: Providing Default Values For The Safe Navigation Operator In Angular 2 Beta 8

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.