Below is the TypeScript file for my service.
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())
}
}
The above code snippet is injected into the component below.
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
}
}
I am trying to display the number of tires in the view of the Home component when the button is clicked. However, I noticed that when I console.log(this.tiresCount)
inside the .subscribe
, it logs 4
but outside of it, it logs undefined
. This suggests that the local property tiresCount
did not receive the updated value and therefore does not display anything in the view.
I feel like I might be overlooking something obvious or perhaps I need a better understanding of Observables and RxJS since I am still relatively new to them.