这是我的服务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组件视图中的轮胎数量。问题是,当我console.log(this.tiresCount)
括号内的.subscribe
时,它会记录4
,但会在其外部记录undefined
。这意味着本地属性tiresCount
没有获取新值,因此它不会在视图中显示任何内容。
我怀疑我错过了一些明显的东西。或许,这里需要了解Observables和/或RxJS,因为我不熟悉它们。
答案 0 :(得分:5)
在订阅方法中使用lambda expression“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
}