【发布时间】:2017-04-20 15:33:59
【问题描述】:
我是 angular 2 的新手,我试图在单击按钮时显示 json 数据,这是我尝试过的,有人可以看看,让我知道我是否以正确的方式进行操作。 我收到以下错误
error_handler.js:56 ORIGINAL EXCEPTION: self.context.getCustomerData is not a function
ErrorHandler.handleError @ error_handler.js:56
error_handler.js:59 ORIGINAL STACKTRACE:
ErrorHandler.handleError @ error_handler.js:59
error_handler.js:60 TypeError: self.context.getCustomerData is not a function
at CompiledTemplate.proxyViewClass.View_AppComponent0.handleEvent_18 (/AppModule/AppComponent/component.ngfactory.js:103)
at CompiledTemplate.proxyViewClass.<anonymous> (view.js:664)
at HTMLButtonElement.<anonymous> (dom_renderer.js:489)
at ZoneDelegate.invokeTask (zone.js:367)
at Object.onInvokeTask (ng_zone.js:264)
at ZoneDelegate.invokeTask (zone.js:366)
at Zone.runTask (zone.js:166)
at HTMLButtonElement.ZoneTask.invoke (zone.js:420)
Thanks in advance
Here is what i did.
html:
<div class="wrapper">
<button type="button" class="btn" (click)="getData()">Click Me</button>
</div>
component:
import { Component } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import "rxjs/Rx";
import { ReturnsJsonArrayService } from '../services/display-json-data.service';
//import {Router} from "@angular/router";
@Component({
selector: 'display-customer-data',
templateUrl:`app/templates/fetch.html`,
providers: [ ReturnsJsonArrayService ]
})
export class DisplayCustomerDataComponent {
data: Observable<Array<any>>;
constructor(private service: ReturnsJsonArrayService) {
this.data = service.getCustomerData();
}
}
service:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from "rxjs/Rx";
import "rxjs/Rx";
@Injectable()
export class ReturnsJsonArrayService {
constructor(private http: Http) {}
getCustomerData(): Observable<any> {
return this.http.get('/app/party-data.json')
// ...and calling .json() on the response to return data
.map((res:Response) => res.json())
//...errors if any
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
}
【问题讨论】:
-
你的
getData方法在哪里? -
你确定
getCustomerData返回的响应是json? -
是的,是@RomanCpan>
-
让我更新帖子@MadhuRanjan
-
给你@MadhuRanjan getData() { return this.http.get('app/party-data.json') // ...并在响应上调用 .json() 返回数据 .map((res:Response) => res.json()) }
标签: javascript json angular angular2-services