如何在 Angular 15 中加载外部脚本?

问题描述 投票:0回答:0

我在我的角度项目中使用 metronic 8 管理面板设计,脚本文件已加载但它不起作用,在 html 版本中工作时,它在角度项目中工作,当我搜索它时,我看到了关于scriptload 服务,我准确地应用了它,但它仍然不起作用。我不知道如何克服这个问题,我希望你能在这方面帮助我。我会尝试用图片解释我遇到的问题,希望它有用,提前感谢您所做的一切。

HTML Version: Header menu is working
HTML Version: Scripts is loaded and working
HTML Version: HTML Code

HTML 版本没有问题。
---------------------------------------------- ----------------------------------------------
Angular Version: Header menu is not working
Angular Version: Scripts is loaded but not working

我在角度项目中使用通过脚本管理器服务导入的脚本,脚本已加载但无法正常工作

[脚本管理器.service.ts]

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

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

export const ScriptStore: Scripts[] = [
  { name: 'plugins.bundle', src: 'assets/plugins/global/plugins.bundle.js' },
  { name: 'scripts.bundle', src: 'assets/js/scripts.bundle.js' },
  { name: 'scripts.custom', src: 'assets/js/scripts.custom.js' },

  { name: 'datatables.bundle.js', src: 'assets/plugins/custom/datatables/datatables.bundle.js' },
  { name: 'widgets.bundle.js', src: 'assets/js/widgets.bundle.js' },
  { name: 'chat.js', src: 'assets/js/custom/apps/chat/chat.js' },
  { name: 'upgrade-plan.js', src: 'assets/js/custom/utilities/modals/upgrade-plan.js' },
  { name: 'create-app.js', src: 'assets/js/custom/utilities/modals/create-app.js' },
  { name: 'users-search.js', src: 'assets/js/custom/utilities/modals/users-search.js' }
];

declare var document: any;

@Injectable({
  providedIn: 'root'
})

export class ScriptManager{

  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('body')[0].appendChild(script);
      } else {
        resolve({ script: name, loaded: true, status: 'Already Loaded' });
      }
    });
  }
}

[index.html]

<!DOCTYPE html>
<html lang="tr" data-bs-theme="dark">
<head>
  <title>Yönetim Paneli</title>
  <base href="/" />
  <meta charset="utf-8" />
  <meta name="description" content="" />
  <meta name="keywords" content="" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="shortcut icon" href="assets/media/logos/blue.favicon.ico" />

  <!--begin::Fonts (mandatory for all pages)-->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Inter:300,400,500,600,700" />
  <!--end::Fonts-->

</head>
<body id="kt_body" data-kt-app-header-stacked="true" data-kt-app-header-primary-enabled="true" class="app-default">
  <div id="kt_app_root" class="d-flex flex-column flex-root app-root"></div>
</body>
</html>

[app-routing.module.ts]

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";

const routes: Routes = [
  { path: '', loadChildren: () => import('./pages/layout/layout.module').then((m) => m.LayoutModule) },
  { path: 'auth', loadChildren: () => import('./pages/auth/auth.module').then((m) => m.AuthModule) },
  { path: 'error', loadChildren: () => import('./pages/error/error.module').then((m) => m.ErrorModule) },
  { path: '**', redirectTo: 'error/not-found', pathMatch: 'full' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

export class AppRoutingModule { }

[app.module.ts]

import { NgModule } from '@angular/core';
import { ScriptManager } from './services/shared/script-manager.service';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from '@app/app-routing.module';
import { HttpClientModule } from '@angular/common/http'

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, AppRoutingModule, HttpClientModule],
  providers: [ScriptManager],
  bootstrap: [AppComponent]
})

export class AppModule { }

[app.component.ts]

import { AfterViewInit, Component } from '@angular/core';
import { ScriptManager } from './services/shared/script-manager.service';

@Component({
  selector: '#kt_app_root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements AfterViewInit {

  constructor(private scriptManager: ScriptManager) { }

  ngAfterViewInit() {
    this.getScriptLoad();
  }

  private getScriptLoad() {
    this.scriptManager.load('plugins.bundle', 'scripts.bundle').then(data => { }).catch(error => console.log(error));
  }
}

[layout-routing.module.ts]

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";

import { LayoutComponent } from "./layout.component";

const routes: Routes = [
  {
    path: '',
    component: LayoutComponent,
    children: [
      { path: '', loadChildren: () => import('../home/home.module').then((m) => m.HomeModule) },
      { path: 'books', loadChildren: () => import('../book/book.module').then((m) => m.BookModule) },
      { path: 'events', loadChildren: () => import('../event/event.module').then((m) => m.EventModule) },
      { path: 'friends', loadChildren: () => import('../friend/friend.module').then((m) => m.FriendModule) },
      { path: 'galleries', loadChildren: () => import('../gallery/gallery.module').then((m) => m.GalleryModule) },
      { path: 'loggings', loadChildren: () => import('../logging/logging.module').then((m) => m.LoggingModule) },
      { path: 'users', loadChildren: () => import('../user/user.module').then((m) => m.UserModule) },
      { path: 'movies', loadChildren: () => import('../movie/movie.module').then((m) => m.MovieModule) },
      { path: 'musics', loadChildren: () => import('../music/music.module').then((m) => m.MusicModule) },
      { path: 'notifications', loadChildren: () => import('../notification/notification.module').then((m) => m.NotificationModule) },
      { path: 'posts', loadChildren: () => import('../post/post.module').then((m) => m.PostModule) },
      { path: 'questions', loadChildren: () => import('../question/question.module').then((m) => m.QuestionModule) },
      { path: 'surveys', loadChildren: () => import('../survey/survey.module').then((m) => m.SurveyModule) },
      { path: 'videos', loadChildren: () => import('../video/video.module').then((m) => m.VideoModule) }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})

export class LayoutRoutingModule { }

我觉得刚接触Angular的朋友都有这个问题,我刚开始使用Angular,还在继续学习,如果你能帮助我解决这个问题,我将不胜感激。谢谢已经回复的朋友们

javascript html angular dom
© www.soinside.com 2019 - 2024. All rights reserved.