2016-07-14 2 views
0

Я делаю Угловой 2 учебник с Hero App. Я нахожусь в Http-части учебника. (link)Угловой 2 затем обещаю

Существует призыв к серверу со следующим методом в hero.service.ts

getHeroes(): Promise<Hero[]> { 
    return this.http.get(this.heroesUrl) 
       .toPromise() 
       .then(response => response.json().data) 
       .catch(this.handleError); 
    } 

И тогда я пытаюсь использовать полученные данные в heroes.components.ts ниже, но Я не могу правильно реализовать функцию then. Я получаю эту ошибку консольного

EXCEPTION: Error: Uncaught (in promise): TypeError: this is null

export class HeroesComponent implements OnInit { 

title = 'Tour of Heroes'; 
heroes: Hero[]; 
selectedHero: Hero; 

constructor(
    private router: Router, 
    private heroService: HeroService) { } 

getHeroes() { 
    this.heroService.getHeroes().then(function(value) { 
     //SUCCESS 
     console.log(value); //this is working 
     this.heroes = value; //this is not working 
     console.log("I am inside then SUCCESS") 
     console.log(title); 
     console.log(this.heroes); 

    }, function(error) { 
     //FAILURE 
     console.log(error); 
    }) 

} 

ngOnInit() { 
    this.getHeroes(); 
} 

Вы знаете, почему я не могу console.log this.heroes и титула?

ответ

4

Возможно, вы захотите рассмотреть обозначение стрелки жира, чтобы избежать scope конфликтов. В вашем случае этот не указывает на экземпляр класса, а на sucesscallback вашего обещания.

getHeroes() { 
    let instance : HeroesComponent = this; 
    this.heroService.getHeroes().then((value) => { 
     //SUCCESS 
     console.log(value); 
     this.heroes = value; 
     console.log("I am inside then SUCCESS") 
     console.log(this.title); 
     console.log(this.heroes); 

    }, (error) => { 
     //FAILURE 
     console.log(error); 
    }) 
} 
0

Вероятно, вы сталкиваетесь с некоторыми проблемами, связанными с определением области охвата ... это то, что он смотрит вверх, это не то, что вы думаете. попробуйте somehting так:

getHeroes() { 
    let that = this; // use that now in all sub functions 
    this.heroService.getHeroes().then(function(value) { 
     //SUCCESS 
     console.log(value); //this is working 
     this.heroes = value; //this is not working 
     console.log("I am inside then SUCCESS") 
     console.log(that.title); 
     console.log(that.heroes); 

    }, function(error) { 
     //FAILURE 
     console.log(error); 
    }) 

} 
1

Это вопрос сферы, в Машинопись есть много вопросов, область видимости при передаче коды JQuery или другого яваскрипт API, и в вашем случае, с лямбда-функциях. Для решения этой проблемы необходимо сохранить область в переменной:

getHeroes() { 
    let instance : HeroesComponent = this; 
    this.heroService.getHeroes().then(function(value) { 
     //SUCCESS 
     console.log(value); //this is working 
     instance.heroes = value; //this now works 
     console.log("I am inside then SUCCESS") 
     console.log(title); 
     console.log(instance.heroes); 

    }, function(error) { 
     //FAILURE 
     console.log(error); 
    }) 

} 

Очень важное замечание: Не используйте _this, чтобы сохранить сферу, потому что это зарезервирован ключевое слово, используемый TypScript для выполнения того же самого действия, но автоматически, что, к сожалению, не работает в комментариях.

1

Благодарим за все ваши ответы. Это вопрос с широким охватом.

You might want to consider fat arrow notation to avoid scope conflicts. In your case, this does not point to the class instance but to the sucesscallback of your promise instead.

Я использовал обозначение жирной стрелки, и это решило проблему.

Смежные вопросы