我试图在模板中呈现Http调用结果但没有成功。 我实际上能够一路回到this.business - 但我无法在视图上呈现它。我错过了什么吗?在这里似乎像魔术一样工作:https://angular.io/docs/ts/latest/cookbook/component-communication.html
这是我的组件:
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);
}
}
我的服务:
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);
}
}
答案 0 :(得分:1)
你应该使用箭头函数而不是胖函数:
@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
将是组件实例(参见箭头函数的词汇)。使用fat函数,this
对应于执行函数的实例,而不是此处的组件实例。因此,您不要在组件实例上设置business
属性...
答案 1 :(得分:1)
据我所知,一切似乎都没问题。仍然使用()=>something
箭头功能,如下所示
getBusiness(){
this.businessService.getBusiness()
.subscribe((business)=>{ //<----added arrow function
this.business = business;
console.log(this.business);
})
.(error) => { this.errorMessage = <any>error}
}