0

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);
  }
}

2 Answers 2

1

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...

Sign up to request clarification or add additional context in comments.

2 Comments

Ah! So in arrow functions, the this skips belonging to the function itself?
To the object where the function is called. See this link for more details: developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
1

According to me everything seems okay. Still go with ()=>something arrow function as shown below

getBusiness(){
    this.businessService.getBusiness()
      .subscribe((business)=>{         //<----added arrow function
          this.business = business;
          console.log(this.business);  
        })
       .(error) => { this.errorMessage = <any>error}
  }

1 Comment

Thanks, @micronyks. Other answerer got in 6 seconds before you, but you both were right :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.