【问题标题】:Using switchMap with Promises将 switchMap 与 Promises 一起使用
【发布时间】:2017-08-10 11:51:23
【问题描述】:

我正在学习 Angular2,遵循 Angular.io 上的“英雄之旅”教程。在教程快结束时,我们设置了到详细信息页面的路由,并传递了一个指示要替换的英雄的参数。这是使用 ActivatedRoute 中的参数 Observable 处理的。我们使用 switchMap 从 params Observable 重定向到 Promise 根据参数返回我们真正想要的数据。

本教程中使用的语法很简洁,因此我尝试将其分解为构建块,以便更好地了解正在发生的事情。具体来说,我尝试将 右箭头符号 替换为我认为相同的实际功能。但是我的修改不起作用。

代码如下:

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."这两个版本的代码看起来和我一模一样。

【问题讨论】:

标签: javascript angular promise observable


【解决方案1】:

胖箭头函数保留执行的上下文,允许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 在此处未定义。

【讨论】:

    【解决方案2】:

    你需要bind你的 getHero 函数。

    .switchMap(this.getHero.bind(this))
    

    否则您的更改是相同的。像这样使用 bind 可以让您将 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'
    

    【讨论】:

      【解决方案3】:

      你不能像在你的 sn-p 中那样使用this.getHero,因为

      1. 它是undefined(服务返回Observable,您必须在使用其数据之前subscribe)
      2. 它不是一个属性(没有get 修饰符)。

      【讨论】:

        猜你喜欢
        • 2017-02-21
        • 2022-01-04
        • 1970-01-01
        • 2016-09-24
        • 2021-09-07
        • 2023-02-22
        • 2019-08-27
        • 1970-01-01
        • 2013-08-26
        相关资源
        最近更新 更多