首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >承诺使用switchMap

承诺使用switchMap
EN

Stack Overflow用户
提问于 2017-01-28 21:31:36
回答 3查看 3.4K关注 0票数 1

我正在学习Angular2,遵循Angular.io上的“英雄之旅”教程。在本教程接近尾声时,我们设置了到详细信息页的路由,并传递一个指示要替换的英雄的参数。这是使用ActivatedRoute中可观察到的params来处理的。我们使用switchMap将可观察到的参数重定向到承诺根据参数返回我们实际需要的数据。

本教程中使用的语法非常简洁,因此我尝试将其分解为构建块,以便更好地理解正在发生的事情。具体来说,我尝试用一个实际的函数替换右箭头符号,我认为它是相同的。但我的修改不管用。

以下是代码:

代码语言:javascript
复制
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.",这两个版本的代码在我看来是相同的。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-01-28 21:51:57

Fat-箭头函数保留执行上下文,允许this“变量”与父作用域中的“变量”相同。如果您使用.switchMap(this.getHero),那么this将指向其他东西,而不是组件。

代码语言:javascript
复制
getHero(params: Params) : Promise<Hero> {
    // "this" is not what you expect here
    return this.heroService.getHero(+params['id']);
}

所以this.heroService在这里是没有定义的。

票数 1
EN

Stack Overflow用户

发布于 2017-08-10 03:51:23

您需要bind您的getHero函数。

代码语言:javascript
复制
.switchMap(this.getHero.bind(this))

否则你的零钱是一样的。像这样使用绑定可以将getHero作为独立函数传递给switchMap,而不会失去this对它的意义。

你可以用它做实验:

代码语言:javascript
复制
'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'
票数 1
EN

Stack Overflow用户

发布于 2017-01-28 21:43:07

不能像在代码片段中那样使用this.getHero,因为

  1. 它是undefined (服务在使用其数据之前必须返回subscribeObservable )。
  2. 它不是属性(没有get修饰符)。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41915043

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档