Answer the question
In order to leave comments, you need to log in
How to force a component to render when it receives data from the server?
Good day!
I appeal to Angular experts. There was such problem:
There is a component which is rendered at application start. It receives data from the service. In turn, the data comes to the service from the server (the assignment takes place via http in the constructor). The problem is that when the application starts, the data does not have time to get into the service variables. And accordingly, errors occur due to the fact that the component accesses data that does not yet exist.
Below is the service code:
import { Injectable, EventEmitter } from '@angular/core';
import { PriceService } from './price.service';
import { Http, Response } from "@angular/http";
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
@Injectable()
export class ModuleDataService {
private datePriceUrl = 'data/data-module.json';
private dataModuleAll: any;
errorMessage: string;
constructor(private priceService: PriceService, private http: Http){
this.http.get(this.datePriceUrl)
.map(this.extractData)
.catch(this.handleError)
.subscribe(
organization => this.dataModuleAll = organization,
error => this.errorMessage = <any>error);
}
getData(){
return this.dataModuleAll;
}
private extractData(res: Response) {
let body = res.json();
return body || { };
}
private handleError (error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
import { Component, OnInit } from '@angular/core';
import { ModuleDataService } from '../../service/data-all.service';
@Component({
moduleId: String(module.id),
selector: 'app-modules',
templateUrl: './app-modules.html',
styleUrls: ['app-modules.css']
})
export class AppModules implements OnInit{
constructor(private moduleDataService: ModuleDataService){ }
ngOnInit(){
this.data = this.moduleDataService.getDataAll();
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question