【发布时间】: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