首页 > 解决方案 > 如何在 Angular 7 中加载自定义 JavaScript 代码

问题描述

我正在尝试在我未找到的组件中加载 js 文件。

我是来自https://www.truecodex.com/course/angular-6/how-to-use-external-js-files-and-javascript-code-in-angular所以,创建文件,添加它在 angular.json 中。在示例中,他们展示了如何使用 onClick 事件来做到这一点。但是当加载未找到的组件并且我不知道该怎么做时,我需要加载这个 js 文件。

import { Component } from '@angular/core';
declare const notFound: any;

@Component({
  selector: 'app-not-found',
  templateUrl: './not-found.component.html',
  styleUrls: ['./not-found.component.css']
})
export class AppComponent {
  title = 'test';

    notFound(); // can't use directly - Function implementation is missing or not immediately following the declaration.ts(2391)
}

当用户加载未找到的页面时,我需要在 not-found.component.ts 和 not-found.component.html 中添加什么来加载此脚本?

标签: javascripthtmlangulartypescript

解决方案


你需要像这样实现 OnInit 接口:

import {Component, OnInit} from '@angular/core';
declare const notFound: any;

@Component({
  selector: 'app-not-found',
  templateUrl: './not-found.component.html',
  styleUrls: ['./not-found.component.css']
})
export class AppComponent implements OnInit{
  title = 'test';
  ngOnInit() {
      notFound();
  } 

}


推荐阅读