![](/img/trans.png)
[英]RXJS Angular - Error handling using .subscribe and Observable
[英]Using RxJS subscribe operator in Angular 2 observable
这是我的服务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,因为我是他们的新手。
在您的订阅方法中使用lambda表达式 “aka,arrow function”而不是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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.