jay*_*ipt 3 rxjs typescript angular
这是我的服务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())
}
}
Run Code Online (Sandbox Code Playgroud)
以上注入到下面的组件中.
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
}
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是在单击按钮时显示Home组件视图中的轮胎数量.问题是,当我console.log(this.tiresCount)在.subscribe括号内时,它会记录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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5552 次 |
| 最近记录: |