http get request returns null on first call- Angular 4

863 views
Skip to first unread message

LJ

unread,
Aug 24, 2017, 5:15:47 PM8/24/17
to Angular and AngularJS discussion
Hi, 
Learning and practicing MEAN for couple weeks now and was able to make http get request api. 

My Angular front end has button and onclick it calls method angular component  -> then service ( all in TS). Service calls express backend to return json data.

Calls sequence & results in same order -->
Angular html page ( button + table of results returned by button click) -> Angular component TS -> Angular Service TS ( http get to express backend here) -> Express Router (Promise End http request to external server)


Angular http request is very simple and not using any fancy apis :
http.get(url).subscribe();

Express usings promise/then and http.request(options, function(res){})

Now, console.log at each level, I noticed that on first button click, my json at component level ( returned by service later)  is null and thus first button click, results are not displayed on page. Second click, it works. 

Why is that so? and do I need to introduce Observables here in Angular Service ?

Sander Elias

unread,
Aug 24, 2017, 10:29:29 PM8/24/17
to Angular and AngularJS discussion
Hi Lj,

Probably there is something off in the way you have wired up processing the results of the get. Normally you never use subscribe in a service.

Regards
Sander

LJ

unread,
Aug 25, 2017, 12:48:40 PM8/25/17
to Angular and AngularJS discussion
Did you mean .subscribe() - is not required for Angular 4.
this.http.get(URL).subscribe(data=>{this.results.data})
this.results = this.http.get(URL)

Are these 2 same? I think i get error that way.

In my issue, above, request is sent on first click and returned back, only that it is not sent back to front page. I can see it logged in service but not back in component. I thought bug is on the front end code somewhere.
Reply all
Reply to author
Forward
0 new messages