简体   繁体   English

Angular 2和打字稿,无法设置未定义的属性

[英]Angular 2 and typescript, cannot set property of undefined

i´m having problem with setting the reviews, This is part of angular 2 project. 我在设置评论时遇到问题,这是angular 2项目的一部分。 The line this.reviews = targ gives me 这行this.reviews = targ给了我
TypeError: Cannot set property 'reviews' of undefined TypeError:无法设置未定义的属性“评论”
The targ seems to exist as i can print it into console succesfully. Targ似乎存在,因为我可以成功将其打印到控制台中。 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();
  }

}

When method references are passed, this doesn't keep pointing to the current class instance by default. 当方法引用传递, this不保留默认指向当前类的实例。 Use .bind(this) or arrow functions to ensure .this points to the current class instance: 使用.bind(this)或箭头函数来确保.this指向当前的类实例:

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

  }  

You are losing the this context if you pass the method like that to the promise . 你失去了this ,如果你通过上下文method类似的promise You should either use an anonymous function wrapper, or bind the this context 您应该使用匿名函数包装器,或绑定this上下文

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. 也不要在TypeScript类中使用function关键字。 This will also cause the this context to get lost. 这也将导致this上下文丢失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM