Angular 7 Service providedIn: 'root' - javascript

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
],

Related

Adding Javascript or importing js file into Angular 9 component

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) {}

Angular9: Import of service not found in component

I've created a service that I use in 2 separate components from the same module.
The service has a few imports and is somewhat normal.
import { CdkPortal } from "#angular/cdk/portal";
import { ElementRef, Injectable } from "#angular/core";
import { Subject, Subscription } from "rxjs";
#Injectable()
export class TestService {...}
I've added the service into the module into the providers array as well as both components where the service is needed.
The first component uses the service with no issue.
import { FlyoutService } from "../flyout.service";
#Component({
selector: "test-uno",
templateUrl: "./test-uno.component.html",
styleUrls: ["./test-uno.component.scss"],
})
export class TestUnoComponent implements OnInit, OnDestroy, AfterViewInit {
constructor(private flyoutService: FlyoutService) {...}
}
The second component, that uses the service in what I think is the same way, fails.
import { FlyoutService } from "./../flyout.service";
#Component({
selector: "test-dos",
templateUrl: "./test-dos.component.html",
styleUrls: ["./test-dos.component.scss"],
animations: [...],
})
export class TestDosComponent implements OnInit, OnChanges, OnDestroy {
constructor(private flyoutService: FlyoutService) { }
}
The second component fails in the browser with the error:
Export of name 'CdkPortal' not found.
This only happens when buildOptimizer is set to true on the build. Any idea what's going on?

Why does this variable always return null ? Angular Service

Its now 8 hours trying to solve a trivial issue & I can't believe it !
here below a script of angular service
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class GetStockDataService {
constructor(public http:HttpClient) { }
RequestData={"query":"{\n stock{\n history{\n \n low\n high\n demand\n }\n }\n}"}
getstockdata(){
return this.http.post('http://localhost:3000/',this.RequestData)
}
}
and here is a component script which is calling that service
import { Component, OnInit } from '#angular/core';
import { GetStockDataService } from '../services/get-stock-data.service';
import { Platform } from '#ionic/angular';
#Component({
selector: 'app-Stocks',
templateUrl: 'Stocks.page.html',
styleUrls: ['Stocks.page.scss']
})
export class StocksPage implements OnInit {
constructor(private GetStockData:GetStockDataService , private platform : Platform) {}
res:any
ngOnInit(){
this.getdata().subscribe(data=>{this.res=data});
console.log(this.res)
}
getdata(){
return this.GetStockData.getstockdata() }}
WHY the "res" variable is always returning NULL ????
knowing that when I put the console log the variable inside there in the function in the subscription part .. it returns data
but I can't make this variable global ... how could I do that ? I just want to get the data from the subscription to the "res" variable to use it the HTML file later .
Due to Async call, console.log(this.res) executes before server call is processed.
Change
this.getdata().subscribe(data=>
{
this.res=data
});
console.log(this.res)
To
this.getdata().subscribe(data=>
{
this.res=data;
console.log(this.res)
});

Angular 6 Universal service provided in Injector needs another app injected variable

I am using Angular Universal. I have created a PlatformService to detect which platform I am currently working on.
/* platform.service.js */
import { Injectable, Inject, PLATFORM_ID } from '#angular/core';
import { isPlatformBrowser, isPlatformServer } from '#angular/common';
#Injectable({
providedIn: 'root'
})
export class PlatformService {
constructor(
#Inject(PLATFORM_ID) private platformId: Object
) {
this.platformId; // this is coming out undefined
}
isBrowser() {
return isPlatformBrowser(this.platformId);
}
isServer() {
return isPlatformServer(this.platformId);
}
}
I am creating a BaseComponent for common handling of my route binded components.
/* base.component.ts */
import { Component, OnInit, Inject } from '#angular/core';
import { InjectorHolderService } from '#core/services/util/injector-holder.service';
import { PlatformService } from '#core/services/util/platform.service';
#Component({
selector: 'app-base',
template: '',
})
export class BaseComponent implements OnInit {
protected platformService: PlatformService;
constructor() {
this.platformService = InjectorHolderService.injector.get(PlatformService);
console.log(this.platformService);
}
}
Since this component will be inherited by many components, I didn't want to pass the PlatformService through super(). So I decided to go with creating an Injector.
/* app.module.ts */
import { InjectorHolderService } from '#core/services/util/injector-holder.service';
import { PlatformService } from '#core/services/util/platform.service';
#NgModule({ ... })
export class AppModule {
constructor() {
InjectorHolderService.injector = Injector.create({
providers: [
{
provide: PlatformService,
useClass: PlatformService,
deps: [], // I think i need to put something here, but not sure.
}
]
});
}
}
And a service which can hold all the injected module for future use.
/* injector-holder.service.ts */
import { Injectable, Injector } from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class InjectorHolderService {
static injector: Injector;
}
But #Inject(PLATFORM_ID) private platformId: Object is giving out undefined, because of which I am not able to detect the platform.
What am I missing here? or If there is a better approach to achieve the above functionality.
Please let me know if you guys need to see any other file.
I am not sure whether the following approach is good or bad, currently, it is the only thing working for me. Would love to hear any new approach to it.
Since PlatformService needed #Inject(PLATFORM_ID) which is provided only from AppModule, the new Injector I created was not able to find any value for #Inject(PLATFORM_ID) and hence undefined.
So, instead of using class PlatformService in Injector, now I am using PlatformService's instantiated object and hence was able to access everything fine in BaseComponent.
Modified my AppModule like following:
/* app.module.ts */
import { InjectorHolderService } from '#core/services/util/injector-holder.service';
import { PlatformService } from '#core/services/util/platform.service';
#NgModule({ ... })
export class AppModule {
constructor(
private platformService: PlatformService,
) {
InjectorHolderService.injector = Injector.create({
providers: [
{
provide: PlatformService,
useValue: this.platformService, // notice the change of key, using value not class
deps: [],
}
]
});
}
}
Will try to add a minimal repo to recreate this issue and share with you guys, If anyone wants to explore more.

angular2 sharing data between components , getters and setters [duplicate]

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.

Categories

Resources