【问题标题】:rest api call to display json data on click of button using angular js 2.0rest api 调用以使用 Angular js 2.0 在单击按钮时显示 json 数据
【发布时间】: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?
  • 是的,是@RomanC​​pan>
  • 让我更新帖子@MadhuRanjan
  • 给你@MadhuRanjan getData() { return this.http.get('app/party-data.json') // ...并在响应上调用 .json() 返回数据 .map((res:Response) => res.json()) }

标签: javascript json angular angular2-services


【解决方案1】:

您好像错过了订阅:

this.data = service.getCustomerData().subscribe(...);

我还强烈建议您将此代码移出构造函数并移入 onInit 生命周期挂钩。这是我的样子:

ngOnInit(): void {
    this._productService.getProducts()
            .subscribe(products => this.products = products,
                       error => this.errorMessage = <any>error);
}

【讨论】:

  • 谢谢@DeborahK,让我试试。
【解决方案2】:

这里有点跑题了,如果我不正确我会删除答案。

既然你说你在点击一个按钮时获得数据,这将是指:

(click)="getData()"

当你写你的问题时,这可能是一个错字,你的意思可能是:

(click)="getCustomerData()"

这是因为像self.context 启动错误这样的错误通常是指该函数不存在。而对你来说不是。您已经在构造函数中声明了它,并且无法从那里获取它。您需要将它放在构造函数之外,以便可以访问它,如下所示:

  constructor(private service: ReturnsJsonArrayService) {
    // leave empty
  }

  getCustomerData() {
    this.data = this.service.getCustomerData()
  }

这样你最终得到了一个 Observable,你需要在模板中应用 async 管道。如果您想使用 POJO,则需要手动 subscribe

  getCustomerData() {
    this.service.getCustomerData()
      .subscribe(data => {
         this.data = data;
      });
  }

如果是这样的话,我建议你看看这个:How do I return the response from an Observable/http/async call in angular2? 因为我们正在处理异步操作。为此,还请查看official docs about http

希望这会有所帮助! :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 2022-01-27
    • 2021-12-29
    相关资源
    最近更新 更多