itamar itamar - 4 months ago 24
AngularJS Question

Rendering Http result Angular2

I am trying to render an Http call result in the template with no success.
I am actually able to make the trip all the way back to this.business - but am unable to render it on the view. Am I missing something? Seems to work like magic here: https://angular.io/docs/ts/latest/cookbook/component-communication.html

Here is my component:

import { Component, OnInit, Input } from '@angular/core';
import { Business } from './business';
import { BusinessService } from './business.service';
import '/app/rxjs-operators';
@Component({
moduleId: module.id,
selector: 'app-business',
templateUrl: 'business.component.html',
styleUrls: ['business.component.css'],
providers:[BusinessService]
})
export class BusinessComponent implements OnInit {
@Input() business: Business;
// business: Business;
errorMessage: string;
mode = 'Observable';
constructor(private businessService: BusinessService) {

}

ngOnInit() {
this.getBusiness();
}

getBusiness(){
this.businessService.getBusiness()
.subscribe(
function(business){
this.business = business;
console.log(this.business); // this outputs correct JSON
},
error => this.errorMessage = <any>error);
}
}


My Service:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Http, Response } from '@angular/http';

import { Business } from './business';

@Injectable()
export class BusinessService {
businessUrl:'http://localhost:8082/business/1';
constructor(private http:Http){}

getBusiness():Observable<Business> {
console.log('http://localhost:8082/business/1');
return this.http.get('http://localhost:8082/business/1')
.map(this.extractData)
.catch(this.handleError);
}

private extractData(res: Response) {
let body = res.json();
console.log(body);
return body || { };
}

private handleError(error:any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}

Answer

You should use an arrow function instead of a fat function:

@Component({
  moduleId: module.id,
  selector: 'app-business',
  templateUrl: 'business.component.html',
  styleUrls: ['business.component.css'],
  providers:[BusinessService]
})
export class BusinessComponent implements OnInit {
  @Input() business: Business;
  // business: Business;
  errorMessage: string;
  mode = 'Observable';

  constructor(private businessService: BusinessService) {

  }

  ngOnInit() {
    this.getBusiness();
  }

  getBusiness(){
    this.businessService.getBusiness()
      .subscribe(
        (business) => { // <-------
          this.business = business;
      );
  }
}

This way this will be the component instance (see lexical this of arrow functions). With a fat function, this corresponds to the instance the function is executed on and not the component instance here. So you set the business property not on the component instance...