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?
A service passed as a parameter in class constructor to be injected as a dependency.
constructor(private testService: TestService) {}
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.
home.compontents.ts constructor should be like below:
constructor(private testService: TestService) {}
Related
I have this error:
Type {...} is missing the following properties from type 'any[]': length,pop,push,concat, and 28 more
I'm assigning album variable to the albumData array. Here is the code:
import { Component, OnInit } from '#angular/core';
import albumData from '../data/SearchResultsAlbum.json';
#Component({
selector: 'app-album-component',
templateUrl: './album-component.component.html',
styleUrls: ['./album-component.component.css']
})
export class AlbumComponentComponent implements OnInit {
album:Array<any>=[];
constructor() { }
ngOnInit(): void {
this.album=albumData;
}
}
What am I doing wrong? Thank you in advanvce!
album:any=[];
use this code instead of the code you have added
By default, Angular doesn't read the JSON file in the application. So we need to do some extra stuff for that. So we will create a file named 'json-typings.d.ts' inside the app folder of the project.
declare module "*.json" {
const value: any;
export default value;
}
source: https://jsonworld.com/demo/how-to-read-local-json-file-in-angular
I'm building an application using angular that keeps track of composers and lists them. However, I keep getting these same two errors every time I try to build and run it. The errors are being found in my composer-details.component.ts file.
I'm fairly new to Angular so any advice would help a ton thank you!
composer-details.component.ts:23:3 - error TS2564: Property 'composer' has no initializer and is not definitely assigned in the constructor.
composer-details.component.ts:26:32 - error TS2345: Argument of type 'string | null' is not assignable to parameter of type 'string'.
composer-details.component.ts
import { Component, OnInit } from '#angular/core';
import { IComposer } from '../composer.interface';
import { ComposerService } from '../composer.service'
import { ActivatedRoute } from '#angular/router';
#Component({
selector: 'app-composer-details',
templateUrl: './composer-details.component.html',
styleUrls: ['./composer-details.component.css']
})
export class ComposerDetailsComponent implements OnInit {
composerId: number;
composer: IComposer;
constructor(private route: ActivatedRoute, private composerService: ComposerService) {
this.composerId = parseInt(this.route.snapshot.paramMap.get('composerId'), 10);
if (this.composerId) {
this.composer = this.composerService.getComposer(this.composerId);
}
}
ngOnInit(): void {
}
}
Try to use ! operator when initializing properties:
composerId!: number;
composer!: IComposer;
I'm very new to angular development so please forgive me if this is a very basic question
But I have a cart service which I have at the moment simply has a simple console log function
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class CartService {
constructor( ) {}
public addItem() {
console.log('Hello');
}
}
and basically I cannot figure out how to use this service within a NG Module that I have installed, I have successfully used it in other components via the constructor but the ngmodule doesn't have this?
I get the fact that it's a singleton at the app-module level by using the providedIn: 'root' tag added in angular 6
but just can't figure out how to call cartService.addItem()?
Thanks if anyone can help!
You can use Dependency Injection like this to call the service
export class AppComponent {
constructor(private cartService: CartService) {
}
doSomething() {
this.cartService.addItem();
}
}
Below is the sample code of how to use service in component:
Component.ts
import { Component, OnInit} from '#angular/core';
import { yourSeerviceName } from "PATH_TO_SERVICE";
#Component({
selector: 'app-dummy',
styleUrls: ['dummy.component.sass'],
templateUrl: 'dummy.component.html'
})
export class yourComponent implements OnInit {
// you can provide any name for variable it's upto you
constructor(private dummyService:yourSeerviceName) {
}
//access the method in you'r service by performing below action.
this.dummyService.yourMethod();
}
If you created a new module, you need to introduce the service to your module, by going to the .module.ts file and adding your service to the providers array. It will be something like:
providers: [
CartService
],
I am new to angular 6. I just start learning angular 6. While creating a project i am stuck into error.
I am simply adding external scripts into my component and getting error
Here is my code
import { Component, OnInit } from '#angular/core';
import * as $ from 'src/assets/js/jquery-3.2.1.min.js';
import 'src/assets/js/countdowntime.js';
#Component({
selector: 'app-comingsoon',
templateUrl: './comingsoon.component.html',
styleUrls: ['./comingsoon.component.css']
})
export class ComingsoonComponent implements OnInit {
constructor() { }
ngOnInit() {
console.log($) // here is am getting output
}
}
Error:
Uncaught ReferenceError: jQuery is not defined at Object..
/src/assets/js/countdowntime.js (countdowntime.js:92)
Update your code
Add jQuery to your index.html or angular.json file
import { Component, OnInit } from '#angular/core';
declare var jQuery:any;
#Component({
selector: 'app-comingsoon',
templateUrl: './comingsoon.component.html',
styleUrls: ['./comingsoon.component.css']
})
export class ComingsoonComponent implements OnInit {
constructor() {
// load countdown
var c = document.createElement("script");
c.type = "text/javascript";
c.src = "src/assets/js/countdowntime.js";
document.getElementsByTagName("head")[0].appendChild(c);
}
ngOnInit() {
console.log(jQuery) // here is am getting output
}
}
You should be able to add jquery as a package and reference it in your component code, so it can get picked up by Webpack:
$ npm add jquery
Then inside your TypeScript code:
import * as $ from 'jquery';
...
export class FooComponent implements OnInit {
ngOnInit() {
console.log($);
}
}
Solution 1 :
Use Jquery types
Need to add types for jquery version.
you can find jquery types here
https://www.npmjs.com/package/#types/jquery
As typescript is strongly typed
For all items which we use in a component should have types
Solution 2 :
create a variable $ and assign its type to any
A workaround if you're not able to find type for the current jquery version which is
declare var $: any;
#Component({
selector: 'app-comingsoon',
templateUrl: './comingsoon.component.html',
styleUrls: ['./comingsoon.component.css']
})
inside your component life cycle check the value of the dollar, you will find jquery properties and method. Your error will be resolved
ngOnInit() {
console.log($)
}
This question already has answers here:
Angular2 - Share data between components using services
(3 answers)
Closed 5 years ago.
I have a question identical to this guy here:
Angular 2 Setter and Getter
The solution que provided thought is not enough for my project to work so I'll explain my situation with some more details to see if you guys can help me!
I have a service dataBase.service.ts :
import {Injectable} from "#angular/core";
#Injectable()
export class dataBaseService{
serviceData: string;
get data():string{
return this.serviceData;
}
set data(value:string){
this.serviceData = value;
}
}
this service is obviously added to app.module.ts as a provider..
on my component A i have:
import { Component, OnInit } from '#angular/core';
import {dataBaseService} from "../dataBase.service";
#Component({
selector: 'app-tipo',
templateUrl: './tipo.component.html',
styleUrls: ['./tipo.component.scss'],
providers: [dataBaseService]
})
export class A implements OnInit {
constructor( public dataService:dataBaseService) {
this.dataService.serviceData = 'hello';
}
ngOnInit() {
console.log(this.dataService.serviceData);
}
}
Until Here everything is fine. If I show on console:
console.log(this.dataService.serviceData); it returns me "hello" as expected
but on my next component when I print again the same data it shows undefinied:
import { Component, OnInit } from '#angular/core';
import {dataBaseService} from "../dataBase.service";
#Component({
selector: 'app-modelo',
templateUrl: './modelo.component.html',
styleUrls: ['./modelo.component.scss'],
providers: [dataBaseService]
})
export class ModeloComponent implements OnInit {
ngOnInit() {
console.log(this.dataService.serviceData);
}
constructor(public dataService: dataBaseService) {
}
}
console.log(this.dataService.serviceData); it returns "undefined"..
So how can I save that data that I putted on the first component and beeing able to show it on another component? what am I missing?
UPDATE:
Some people like me didn't find an answer to the other question like this one on stack and that's because Instead of adding the providers individually you have to add them globably (on module.ts) !!!!!!!!!!!!
As you said you have already added the provider on the module level,try commenting out the providers declaration from components.