1

i´m having problem with setting the reviews, This is part of angular 2 project. The line this.reviews = targ gives me
TypeError: Cannot set property 'reviews' of undefined
The targ seems to exist as i can print it into console succesfully. Any ideas why this is happening?

import { ReviewService } from '../review.service';
import { Review } from '../review/review.component'
import { Component} from '@angular/core';
import {  OnInit } from '@angular/core';

@Component({
  selector: 'review-list',
  templateUrl: './review-list.component.html',
  styleUrls: ['./review-list.component.css'],
  providers: [ReviewService] //for the injector to be able to inject ReviewerService
})

export class ReviewListComponent implements OnInit {
   public reviews: Review[];

  constructor(private reviewService: ReviewService) {
    this.reviews = [] ;
  }


  initializeReviews(): void {
     this.reviewService.getReviews().then(
        this.set    
     ).catch(function(reason){
        console.log(reason);
     });

  }  



  set(targ):void {
    console.log(targ);
    this.reviews = targ;

  }

  ngOnInit(): void {
    this.initializeReviews();   
    //this.reviews = this.reviewService.get();
  }

}
0

2 Answers 2

2

When method references are passed, this doesn't keep pointing to the current class instance by default. Use .bind(this) or arrow functions to ensure .this points to the current class instance:

  initializeReviews(): void {
     this.reviewService.getReviews().then(
        this.set.bind(this) // << add `.bind(this) or
        // (val) => this.set(val)    
     ).catch(function(reason){
        console.log(reason);
     });

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

Comments

2

You are losing the this context if you pass the method like that to the promise. You should either use an anonymous function wrapper, or bind the thiscontext

initializeReviews(): void {
   this.reviewService.getReviews().then((response) => {
       this.set(response);
   })
   .catch((reason) => {
    console.log(reason);
   });
} 

or

this.reviewService.getReviews().then(this.set.bind(this))

Also never use the function keyword inside a TypeScript class. This will also cause the this context to get lost.

1 Comment

sorry. I had a confusion with the bind method. Thanks.

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.