Reputation: 67
I'm new to Angular and creating a project that that uses routing. I'd like to import a js file from src/assets/js/custom.js
I've created a service that imports an injectable like so
test.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class TestService {
testFunction() {
console.log('Test');
}
}
home.compontents.ts looks like
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();
}
}
But I am getting the following error
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 }
~
I've tried so many different ways from Google searches and not coming up with anything. Can anyone please help?
UPDATE
Thanks for the updates, I've updated the constructor, however I am getting an error
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';
I'm not sure if I am going the right way with this. Each component I am using has 1 or 2 js files that I need to import. What would be the best way to do this?
Upvotes: 0
Views: 316
Reputation: 1245
A service passed as a parameter in class constructor to be injected as a dependency.
constructor(private testService: TestService) {}
Upvotes: 3
Reputation: 683
home.compontents.ts constructor should be like below:
constructor(private testService: TestService) {}
Upvotes: 0
Reputation: 213
The constructor is written incorrectly. Please write it as given below
constructor(private testService: TestService) {}
Also, you have given service as @Injectable()
,then you have to define the service in app.module.ts
file.
Alternatively, you can give
@Injectable({
providedIn: 'root'
})
This will eliminate adding the service in providers.
Upvotes: 1