[英]Adding Javascript or importing js file into Angular 9 component
我是 Angular 的新手,我正在创建一个使用路由的项目。 我想从 src/assets/js/custom.js 导入一个 js 文件
我创建了一个像这样导入可注射的服务
测试服务.ts
import { Injectable } from '@angular/core';
@Injectable()
export class TestService {
testFunction() {
console.log('Test');
}
}
home.components.ts 看起来像
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { TestService } from './test.service';
declare var require: any
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss'],
providers: [TestService]
})
export class HomeComponent implements OnInit {
constructor() {private testService: TestService}
ngOnInit(): void {
this.testService.testFunction();
}
}
但我收到以下错误
17 constructor() {private testService: TestService}
~~~~~~~
src/app/home/home.component.ts:19:13 - error TS1005: ';' expected.
19 ngOnInit(): void {
~
src/app/home/home.component.ts:20:9 - error TS1005: ':' expected.
20 this.testService.testFunction();
~
src/app/home/home.component.ts:20:36 - error TS1005: ',' expected.
20 this.testService.testFunction();
~
src/app/home/home.component.ts:24:1 - error TS1128: Declaration or statement expected.
24 }
~
我从谷歌搜索中尝试了很多不同的方法,但没有提出任何建议。 有人可以帮忙吗?
更新
感谢您的更新,我已经更新了构造函数,但是我收到了一个错误
ERROR in src/app/home/home.component.ts:3:29 - error TS2307: Cannot find module './test.service' or its corresponding type declarations.
3 import { TestService } from './test.service';
我不确定我是否走对了这条路。 我使用的每个组件都有 1 或 2 个需要导入的 js 文件。 最好的方法是什么?
在 class 构造函数中作为参数传递的服务作为依赖项注入。
constructor(private testService: TestService) {}
构造函数写错了。 请按如下所示写
constructor(private testService: TestService) {}
此外,您已将服务提供为@Injectable()
,然后您必须在app.module.ts
文件中定义服务。 或者,您可以给
@Injectable({
providedIn: 'root'
})
这将消除在提供程序中添加服务。
home.compontents.ts 构造函数应该如下所示:
constructor(private testService: TestService) {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.