Reputation: 937
I have two services config, auth which have a code similar to this :
public init = (): Observable<AppConfig> => {
return this._http.post(this.actionUrl, JSON.stringify(this.APP_CONFIG), { headers: this.headers })
.map((response: Response) => response.json() as AppConfig)
.catch(this.handleError);
}
And these two services are called in one final service which will be called on every components in my Angular 5 application :
@Injectable()
export class PageService {
constructor(private configService: ConfigService, private authService: AuthService) { }
config: AppConfig;
auth: Auth;
grants: Grants;
init() {
Observable.forkJoin(
this.configService.init(),
this.authService.init(),
this.authService.grants())
.subscribe(
data => {
this.config = data[0];
this.auth = data[1];
this.grants = data[2];
// Logs
console.log(this.config);
console.log(this.auth);
console.log(this.grants);
});
}
}
Here is how I call it in my component :
export class DashboardComponent implements OnInit {
columns: any[];
constructor(private pageService: PageService) { }
ngOnInit() {
this.pageService.init();
this.userAccessPanel();
}
userAccessPanel = () => {
console.log('Grant : ', this.pageService.grants);
}
}
The problem is that this.pageService.grants
shows undefined I guess because it's called before I could get the data from the server. But in that case I couldn't find any way on the internet to solve my problem.
How can I do to launch this.userAccessPanel()
after being sure this.pageService.init()
finished and got all the data from the server ?
Thank in advance
Upvotes: 0
Views: 1026
Reputation: 11380
init() has to return an observable
init() {
return Observable.forkJoin(
this.configService.init(),
this.authService.init(),
this.authService.grants())
.map(([config,auth,grants])=>{config,auth,grants})
}
then in your other component
ngOnInit() {
this.pageService.init()
.map(obj=>this.userAccessPanel(obj.grants)).subscribe()
}
userAccessPanel = (grants) => {
console.log('Grant : ', grants);
}
Upvotes: 1