I call in my app construct() function a external json url, in console log I see correct result of:
var url = 'https://my_path.co/apiv1/products';
this.http.get(url).map(res => res.json()).subscribe(items => console.log(items));
How can I pass this result to my view and render with *ngFor?
Not a good place for this. Do it instead in an injectable service provider’s constructor, so your question becomes simple: just inject the provider in whatever page needs to display the information.
Don’t do anything hard in a constructor. It slows down your page rendering. Also, you have access to ES6, so it’s much better to use let, and stop using var. Putting the work in a provider is the best approach to scale. But to give you an idea, here is a not-very-good way to do this:
const url = 'https://my_path.co/apiv1/products';
products = Observable<whateverTypeTheProductListIs> = new Observable<whateverTypeTheProductListIs>();
products = this.http.get(url).map(res => res.json());
And in the template, use
I wouldn’t classify firing off an asynchronous HTTP request “hard”.
Ha, I more or less believe, “Don’t do anything at all in a constructor!”
This is one situation where I feel a service provider constructor is absolutely the right place: where you are initiating a fetch for data from an external source that you want to be available throughout the app as soon as reasonably possible. I don’t think it introduces any rendering overhead, as we are off the main thread almost immediately.
Yeah, I should change my not-completely-silly rule to, “Do nothing in a page constructor.” I do things in provider constructors because why not, that doesn’t slow down page rendering. Though (for the reader who does not know) the constructor is run the first time the provider is injected and used, so if you have a heavy operation that only some pages use, it’s probably better to keep it in a doHeavyOperation() method, instead of the constructor, because otherwise a page that doesn’t need the heavy operation might pay for it anyway.
A proposed exception: putting reactive forms together using
FormBuilder. I used to try delaying that to various lifecycle handlers (notably
ionViewDidLoad) and encountered more trouble than I considered it worth.
I had the same experience. I can’t help thinking there’s something I missed, but I broke down and put the FormGroups in a constructor. (Well, not exactly true, I put a call to refreshForm() in the constructor, and define a custom form refresher that I can call from other methods. But it’s the same idea.)