Angular 4路由器未加载组件

时间:2018-08-07 18:43:10

标签: html angular angular4-router

我正在尝试为一家建筑公司构建Angular项目,为此我从一个正版网站下载了html模板。现在,我试图将代码迁移到Angular4。我在项目中实现了路由器概念,以导航到不同的页面。

下面是项目结构-

src 
|_
   app
    |_aboutus
    |_home
    |_app_root(app.component.html)
  |_assets
  |_index.html

因此,我已经将我的所有CSS和外部js文件都包含在index.html页面中,该页面将在所有组件中使用。在app.component.html中,我将导航栏放在了下面

<router-outlet> </router-outlet>

标签。我在home和aboutus组件中有我的html代码。以下是我的app.module.ts文件-

 imports: [
    BrowserModule,
    RouterModule.forRoot([
      {
         path: 'about-us',
         component: AboutusComponent
      },
      {
        path: 'home',
        component: HomeComponent
     },
     {
      path: '',
      component: HomeComponent
     }
   ])
  ]

现在,如果我运行localhost:4200,则默认情况下将呈现home组件的视图。当我点击aboutus pae时,它会渲染少量文本,并且无法加载动画。但是,如果我这样直接访问aboutus页面(localhost:4200 / about-us),则可以加载数据。我的问题是我在这里进行路由有什么问题? 有关代码参考-https://github.com/chikun525/RetroBuildConNew

1 个答案:

答案 0 :(得分:1)

您必须动态加载JavaScript文件:

DynamicScriptLoaderService

import { Injectable } from '@angular/core';

interface Scripts {
  name: string;
  src: string;
}

export const ScriptStore: Scripts[] = [
  { name: 'chartjs', src: 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js' },
  { name: 'random-gen', src: '../../../assets/js/random-num-generator.js' }
];

declare var document: any;

@Injectable()
export class DynamicScriptLoaderService {

  private scripts: any = {};

  constructor() {
    ScriptStore.forEach((script: any) => {
      this.scripts[script.name] = {
        loaded: false,
        src: script.src
      };
    });
  }

  load(...scripts: string[]) {
    const promises: any[] = [];
    scripts.forEach((script) => promises.push(this.loadScript(script)));
    return Promise.all(promises);
  }

  loadScript(name: string) {
    return new Promise((resolve, reject) => {
      if (!this.scripts[name].loaded) {
        //load script
        let script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = this.scripts[name].src;
        if (script.readyState) {  //IE
            script.onreadystatechange = () => {
                if (script.readyState === "loaded" || script.readyState === "complete") {
                    script.onreadystatechange = null;
                    this.scripts[name].loaded = true;
                    resolve({script: name, loaded: true, status: 'Loaded'});
                }
            };
        } else {  //Others
            script.onload = () => {
                this.scripts[name].loaded = true;
                resolve({script: name, loaded: true, status: 'Loaded'});
            };
        }
        script.onerror = (error: any) => resolve({script: name, loaded: false, status: 'Loaded'});
        document.getElementsByTagName('head')[0].appendChild(script);
      } else {
        resolve({ script: name, loaded: true, status: 'Already Loaded' });
      }
    });
  }

}

在component.ts

// Angular
import { Component, OnInit } from '@angular/core';

// Service
import { DynamicScriptLoaderService } from '../../shared/services/dynamic-script-loader.service';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html'
})
export class DashboardComponent implements OnInit {


  constructor(private dynamicScriptLoader: DynamicScriptLoaderService) {}

  ngOnInit() {
    // Just call your load scripts function with scripts you want to load
    this.loadStripeScripts();
  }

  private loadChartScripts() {
    // You can load multiple scripts by just providing the key as argument into load method of the service
    this.dynamicScriptLoader.load('chartjs','random-num').then(data => {
      // Script Loaded Successfully
    }).catch(error => console.log(error));
  }

}

不要忘记将服务添加到您的app.module

providers: [
        DynamicScriptLoaderService
    ],

来源:https://medium.com/@zainzafar/angular-load-external-javascript-file-dynamically-3d14dde815cb

编辑:

这是一种解决方法: 在您要执行的Javascript文件中,将该文件的所有代码放入函数中,例如:

function myFunction() {
    alert("hello world");
    // here's goes all the javascript code
}

在您的组件(AboutusComponent)的html文件中,将以下标记放在某处:

<button onclick="myFunction()" id="scriptCall" style="display: none"></button>

并在组件(AboutusComponent)的ngOnInit方法中放入以下代码

 var scriptCall = document.getElementById('scriptCall');
 scriptCall.click();