1

Hello fellow Programmer,

we have an component which loads after clicking on a link, this components content depends on the the link its got clicked. For Example we click on the Link and load a JSON from an API which contain the Data, this Data is shown on our HTML template.

So far we have an succesfull API call which gets us the JSON and we bind it on an var which is conected to the HTML by {{var}}, but it wont display the JSON at all.

We are pretty sure it is a problem with the asynchron call from the API to get the Data, but we have no idea how to fix this.

component.service.ts with the getVoucher() method

getVoucher() {

  let voucherUrl = 'xxx';  // URL to web api
  let headers = new Headers();
  headers.append('Content-Type', 'application/json;charset=UTF-8');
  headers.append('Authorization', 'Basic '+btoa("xxx"));

  let options = new RequestOptions({ headers: headers });
  return this.http.get(voucherUrl,options).map(response => response.json());

}

component.ts

private gutschein;
private strGutschein;

ngOnInit(): void {

    this.voucherService.getVoucher().subscribe(data => {
        this.gutschein = data;
        console.log(this.gutschein);
    });

    setTimeout(() => console.log(this.gutschein), 2000); 
    //console.log(this.gutschein);
    this.strGutschein = JSON.stringify(this.gutschein);
}

and the HTML Part component.html

{{strGutschein}}
Amit kumar
  • 6,029
  • 6
  • 30
  • 40
sHamann
  • 789
  • 3
  • 10
  • 36
  • Your questions logic is the same as the last one. You need to assign `strGutschein` inside the subscribe. – eko Apr 05 '17 at 10:27
  • set `this.strGutschein = JSON.stringify(this.gutschein);` in `subscribe`..it is asynchronous – Suraj Rao Apr 05 '17 at 10:28
  • @echonax its not, last time i asked for the Problem itself with the console Output. – sHamann Apr 05 '17 at 10:29
  • 1
    @sHamann `this.gutschein` is `undefined` by the time you make the assignment. `getVoucher` is async as suraj said. That was the reason why your `console.log` was printing `undefined`. It **is** the same problem. – eko Apr 05 '17 at 10:30

1 Answers1

1

your component code should be like this

private gutschein;
private strGutschein;

ngOnInit(): void {

    this.voucherService.getVoucher().subscribe(data => {
        this.gutschein = data;
        console.log(this.gutschein);
        this.strGutschein = JSON.stringify(this.gutschein);
        console.log(this.strGutschein);
    });
    setTimeout(() => console.log(this.gutschein), 2000);     
}

and in html part use

{{ strGutschein | json }}
Amit kumar
  • 6,029
  • 6
  • 30
  • 40
  • We are trying to teach OP how async behaviour works. If you check OPs other question you will see the logic is the same. Won't you consider it as a duplicate? And why are you using json pipe on a string? – eko Apr 05 '17 at 10:56
  • @echonax Actually i understood how async works, but i couldnt find a solution, anyway the idea of Amit worked fine. may you guys can tell me which would be better to use in my case, the subsricbe method or use an promise ? – sHamann Apr 05 '17 at 10:57
  • @sHamann suraj already told you to do the assignment inside the subscribe in the comments. And in the link that I've given it says to do the async operations inside the subscribe callback. I still don't think you understood how async operations work. What do you mean by using a promise? You already subscribe to an observable which is an abstracted promise. – eko Apr 05 '17 at 11:01
  • @echonax in this question he is saying he is not able to see JSON which he got from api response and you can not see json directly in html – Amit kumar Apr 05 '17 at 11:02
  • echonax i will check his other question. don't worry. :) – Amit kumar Apr 05 '17 at 11:03
  • @AmitSuhag `strGutschein` is `string`. You are using json pipe to a `string`. The reason OP can't see it in the html is that `strGutschein` is `undefined` because of the async operation as you've answered. The pipe is redundant. – eko Apr 05 '17 at 11:05
  • @echonax i think strGutschein is json. not string. if he is getting string from api. then why he is using JSON.stringify ? read his question once more my friend. JSON.stringify(this.gutschein) what that suppose to mean then. he is using stringify on a string ? – Amit kumar Apr 05 '17 at 11:09
  • Its still nice to Know about the pipe, so i can review this function later, im just getting in touch with Angular2. If i do understand correctly an observable is like a watcher if the data-stream recieves any changes, the promises is a one time execution which will handle asynch, right? – sHamann Apr 05 '17 at 11:10
  • 1
    @AmitSuhag `this.gutschein` is a json `strGutschein` is a string. Because `this.strGutschein = JSON.stringify(this.gutschein);`. The output of `JSON.stringify` is a `string` my friend. – eko Apr 05 '17 at 11:11
  • @echonax since i only do one API call which gives me the data i work on them and put it back to the API server, wouldnt be a promise better solution than my current observable? – sHamann Apr 05 '17 at 11:15
  • @sHamann Check this answer http://stackoverflow.com/questions/38008334/angular2-rxjs-when-should-i-unsubscribe-from-subscription if you want a promise, you can easily convert an observable to a promise by simply adding the `.toPromise()` method before the subscribe. – eko Apr 05 '17 at 11:16