簡體   English   中英

添加Javascript或將js文件導入Angular 9組件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM