【问题标题】:Using RxJS subscribe operator in Angular 2 observable在 Angular 2 observable 中使用 RxJS 订阅运算符
【发布时间】:2016-05-08 13:06:24
【问题描述】:

这是我的服务 TypeScript 文件。

import {Injectable} from '@angular/core';
import {Http, HTTP_PROVIDERS, Request, RequestOptions, Response, Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class CarService {
    constructor(private http: Http) { }
    Url: string = 'url/of/api';
    getCar(){
        var headers = new Headers();
            headers.append('API-Key-For-Authentification', 'my_own_key_goes_here');
            headers.append('Accept', 'application/json');
        var options = new RequestOptions({ headers: headers })
        return this.http.get(this.Url, options)
            .map((res: Response) => res.json())
    }
}

上面被注入到下面的组件中。

import {Component} from '@angular/core';
import {CarService} from 'path/to/car.service';

@Component({
    selector: 'home',
    providers: [ CarService ],
    template: `
        <div>
            <button (click)="getCar()">Get Car</button>
            <h2>The car has {{ tiresCount }} tires.</h2>
        </div>
    `
})
export class Home {
    tiresCount: number;
    constructor(private carService: CarService) { }
    getCar() {
        this.carService.getCar()
            .subscribe(function(data){
                this.tiresCount = data.tires.count;
                console.log(this.tiresCount); // 4
        };
        console.log(this.tiresCount); // undefined
    }
}

我要做的是在单击按钮时在 Home 组件的视图中显示轮胎的数量。问题是,当我在.subscribe 括号内使用console.log(this.tiresCount) 时,它会记录4,但会在其外部记录undefined。这意味着本地属性tiresCount 没有获得新值,因此它不会在视图中显示任何内容。

我怀疑我遗漏了一些明显的东西。或者,由于我是新手,所以这里需要对 Observables 和/或 RxJS 的理解。

【问题讨论】:

  • 在这种情况下,Observables 的功能与 Promise 几乎相同......本质上是异步的。因此,您期望您的外部 console.log 在运行时会被定义,但它不会。它会触发对 getCar 的调用,然后在返回异步响应之前点击外部 console.log。
  • 有道理,但我也想了解为什么本地属性tiresCount在返回响应后没有收到新值。

标签: typescript angular rxjs


【解决方案1】:

在您的订阅方法中使用 lambda expression "aka,箭头函数" 而不是 function(){..}。当使用function(){...}时,里面的this会引用函数本身而不是Home组件类。

getCar() {
    this.carService.getCar()
            .subscribe(data => {
                this.tiresCount = data.tires.count;
                console.log(this.tiresCount); // 4
    });
    console.log(this.tiresCount); // undefined
}
someWhereElse(){
    console.log(this.tiresCount); // 4 , only after getCar().subscribe() resolves 
}

【讨论】:

  • 这行得通。 this 所指的内容至关重要。另外,我不知道 lambda 表达式的语法需要在语句周围使用 { }。我先尝试不使用它们,但它不起作用,所以我改用function(){..},这不是一个好主意。谢谢!
  • 不客气@jayscript,除非正文是多行的,否则 lambda 表达式 not 需要 {...}。否则你可以.subscribe(data=&gt;this.tiresCount=data.tires.count)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-28
  • 2018-01-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
相关资源
最近更新 更多