Reputation: 12174
I have a component that loads a map during ngAfterViewChecked
.
I have a service that I want to run after the map is fully-loaded in #map
div element.
Once the map is properly/fully loaded, #map
now has canvas
children.
The problem right now is, I don't know what's the PROPER way of initiating a service once the canvas
elements in the #map
are present.
map.component.ts
1st version:
ngAfterViewChecked() {
this.map.load();
console.log(window['something']); // DOESNT WORK
// this.service.run();
}
2nd version:
ngAfterViewChecked() {
this.map.load().then(res => {
console.log(window['something']); // DOESNT WORK
// this.service.run();
});
}
map.service.ts
public load() {
return new Promise(resolve => {
let node = document.createElement('script');
node.src = '/Scripts/map-loader.js';
node.type = 'text/javascript';
node.async = true;
node.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(node);
});
}
It's pretty tough since the map loader is an external Javascript.
Really hoping for someone to shed some light.
EDITED [UPDATED CODE]
map.component.ts
import { Component, AfterViewChecked } from '@angular/core';
import { ConfigService } from '../../service/service.config';
import { RequestService } from '../../service/service.request';
import { MapRenderService } from '../../service/map-render.service';
@Component({
templateUrl: './app/component/map/map.component.html'
})
export class MapComponent implements AfterViewChecked {
constructor(private send: RequestService, private config: ConfigService, private mapRender: MapRenderService) {
}
ngAfterViewChecked() {
this.mapRender.load().then(res => {
console.log(window['micello']); // ALWAYS PRINTS HERE
});
}
}
map-render.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class MapRenderService {
private loader = '/Scripts/map-loader.js';
public load() {
return new Promise(resolve => {
let node = document.createElement('script');
node.src = '/Scripts/map-loader.js';
node.type = 'text/javascript';
node.async = true;
node.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(node);
resolve();
});
}
}
Console Output
Upvotes: 0
Views: 73
Reputation: 9331
You are missing the resolve
call in promise .
Change service to this.
public load() {
return new Promise(resolve => {
let node = document.createElement('script');
node.src = '/Scripts/map-loader.js';
node.type = 'text/javascript';
node.async = true;
node.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(node);
resolve();
});
}
And run the 2nd version with then
Upvotes: 1