I am trying to simply bind a variable in a template in Angular2 to a variable of a service. The service should load the data via http and then update the view in the template accordingly again (I assume change detection should do that and the binding as well). Yet I cannot get this to work. The initial value of the variable in the service is displayed. The http request is also performed and IMHO sets the variable back again. Yet the view is not updated.
import {Component} from 'angular2/core';
import {HTTP_PROVIDERS, Response, Http} from 'angular2/http';
@Component({
providers: []
})
export class AddressService{
ipaddress: String='evaluating';
constructor(private http:Http) {}
getIp(){
this.http.get('http://ip.jsontest.com/')
.subscribe(
data => this.processResponse(data.json()),
err => this.logError(err)
);
}
logError(err) {
console.error('There was an error: ' + err);
}
processResponse(data){
console.log(data.ip);
this.ipaddress='data.ip';
}
}
@Component({
selector: 'address-app',
template: '<div>your IP Address is: {{addressService.ipaddress}}</div>',
providers: [AddressService]
})
export class App {
constructor(private addressService: AddressService){
this.addressService.getIp();
}
}
with a simple boot.ts bootstrapping the app
import {bootstrap} from 'angular2/platform/browser'
import {HTTP_PROVIDERS} from 'angular2/http';
import {App} from 'app.ts'
bootstrap(App, [HTTP_PROVIDERS]);
I created a plunker for this http://plnkr.co/edit/75VVjEUSflbvh3oG8Kwk?p=preview where the service simply requests the IP and then should update the display - yet this remains on the original value (evaluating). This was easy and straight forward in Angular 1 and I am not sure what I am doing wrong here to get the same result in Angular 2.
You should add angular2-polyfills
to your project (see this plunk):
<script src="//code.angularjs.org/2.0.0-beta.0/angular2-polyfills.min.js"></script>
PS Please, don't use @Component
decorator for services. Use @Injectable
instead.