0

I am new to angular 2 ,and i am trying to display json data on click of a button, this is what i have tried,can someone take a look and let me know if i am doing it in the right way. I am getting the below error

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

    }
OptimusPrime
  • 85
  • 2
  • 4
  • 12

2 Answers2

0

It looks like you are missing the subscribe:

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

I'd also highly recommend that you move this code out of the constructor and into the onInit lifecycle hook. Here is what mine looks like:

ngOnInit(): void {
    this._productService.getProducts()
            .subscribe(products => this.products = products,
                       error => this.errorMessage = <any>error);
}
DeborahK
  • 57,520
  • 12
  • 104
  • 129
0

Going a bit out on a limb here, I will delete answer if I'm incorrect.

Since you said you are getting data on click of a button, which would refer to:

(click)="getData()"

This would be a typo when you wrote your question, you probably mean it to be:

(click)="getCustomerData()"

This is figured out since an error like self.context starting error usually refers to that the function does not exist. And for you it doesn't. You have declared it inside the constructor, and it cannot be fetched from there. You need to place it outside the constructor so that it can be reached, like so:

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

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

This way you end up with an Observable, to which you need to apply the async pipe in the template. If you instead want to work with POJO, you need to manually subscribe:

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

And if that is the case, I suggest you take a look at this: How do I return the response from an Observable/http/async call in angular2? Since we are dealing with an async operation. For this, also check out the official docs about http.

Hope this helps! :)

Community
  • 1
  • 1
AT82
  • 71,416
  • 24
  • 140
  • 167