我正在学习Angular2,遵循Angular.io上的“英雄之旅”教程。在本教程接近尾声时,我们设置了到详细信息页的路由,并传递一个指示要替换的英雄的参数。这是使用ActivatedRoute中可观察到的params来处理的。我们使用switchMap将可观察到的参数重定向到承诺根据参数返回我们实际需要的数据。
本教程中使用的语法非常简洁,因此我尝试将其分解为构建块,以便更好地理解正在发生的事情。具体来说,我尝试用一个实际的函数替换右箭头符号,我认为它是相同的。但我的修改不管用。
以下是代码:
ngOnInit(): void {
this.route.params
.switchMap((params: Params) => this.heroService.getHero(+params['id']))
//.switchMap(this.getHero)
.subscribe(hero => this.hero = hero);
}
getHero(params: Params) : Promise<Hero> {
return this.heroService.getHero(+params['id']);
}让我困惑的是,为什么使用当前被注释掉的行而不是上面的行,我会得到一个错误:"Cannot read property 'getHero' of undefined.",这两个版本的代码在我看来是相同的。
发布于 2017-01-28 21:51:57
Fat-箭头函数保留执行上下文,允许this“变量”与父作用域中的“变量”相同。如果您使用.switchMap(this.getHero),那么this将指向其他东西,而不是组件。
getHero(params: Params) : Promise<Hero> {
// "this" is not what you expect here
return this.heroService.getHero(+params['id']);
}所以this.heroService在这里是没有定义的。
发布于 2017-08-10 03:51:23
您需要bind您的getHero函数。
.switchMap(this.getHero.bind(this))否则你的零钱是一样的。像这样使用绑定可以将getHero作为独立函数传递给switchMap,而不会失去this对它的意义。
你可以用它做实验:
'use strict';
const foo = {
bar: 'baz',
getBar: function() {
return this.bar;
}
};
foo.getBar();
// => 'baz'
const myGetBar = foo.getBar;
myGetBar();
// => TypeError: Cannot read property 'bar' of undefined
const boundGetBar = foo.getBar.bind(foo);
boundGetBar();
// => 'baz'
const otherObj = { bar: 'hi' };
const otherBoundGetBar = foo.getBar.bind(otherObj);
otherboundGetBar();
// => 'hi'
otherObj.getBar = myGetBar;
otherObj.getBar();
// => 'hi'发布于 2017-01-28 21:43:07
不能像在代码片段中那样使用this.getHero,因为
undefined (服务在使用其数据之前必须返回subscribe的Observable )。get修饰符)。https://stackoverflow.com/questions/41915043
复制相似问题