rest api调用在使用angular js 2.0点击按钮时显示json数据

时间:2017-04-20 15:34:00

标签: javascript json angular angular2-services

我是角度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'));
      }

    }

2 个答案:

答案 0 :(得分:0)

看起来你错过了订阅:

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

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

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

答案 1 :(得分:0)

如果我不对劲,我会删除答案。

因为您说您正在获取点击按钮的数据,这将参考:

(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

希望这有帮助! :)