加载外部脚本后无法访问组件

Unable to access component after external script loaded

我正在尝试在 angular6 应用程序中加载 Google API。触发加载事件后,我无法真正更改组件中的任何内容。

看看脚本最后 3 行的注释

@Component({
  selector: 'my-app',
  template: '{{loaded}}',
})
export class AppComponent  {
  loaded = false;   
  constructor(){
    let node = document.createElement('script');
    node.src = 'https://apis.google.com/js/client.js?onload=__onGoogleLoaded';
    node.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(node);

    window['__onGoogleLoaded'] = (ev) =>{
      console.log('here!!!!');// <----------------------------WORKING
      this.loaded = true;// <---------------------------------NOT WORKING
    }
    //this.loaded = true; <<----------------------------------WORKING
  }
}

https://stackblitz.com/edit/angular-qvwm3z?file=src%2Fapp%2Fapp.component.ts

添加 ChangeDetectorRef 以强制您的应用检查组件中的任何更改

通过这样做

  constructor(
    private changeRef: ChangeDetectorRef
  ){
    let node = document.createElement('script');
    node.src = 'https://apis.google.com/js/client.js?onload=__onGoogleLoaded';
    node.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(node);

    window['__onGoogleLoaded'] = (ev) =>{
      console.log('here!!!!');// <----------------------------WORKING
      this.loaded = true;// <---------------------------------NOT WORKING
      this.changeRef.detectChanges(); <<---------------------------------- add this one
    }
    //this.loaded = true; <<----------------------------------WORKING
  }