how to define initial state for Angular service - javascript

Don't know i have to ask or not but just came thought in mind so asking.
i have situation like some service or class variable value i have modified after doing some operation inside component but is there any way to get what was the service or class initial state before modified by this component.
MyService
#Injectable()
export class MyService {
public a = "";
public b = false;
public c = "";
...
}
MyComponent
#Component({
selector: 'mycomp',
templateUrl: './mycomp.component.html',
styleUrls: ['./mycomp.component.styles.scss']
})
export class MyComponent implements OnInit {
constructor(private myService: MyService) {
}
ngOnDestroy() {
this.myService.a = "";
this.myService.b = false;
this.myService.c = "";
...
}
}
because my service contains thousands of variables,and i want to reset all service variables modified by the component, on component destroy.
is it possible to reset initial stage for the Service class?
Thanks.

Related

Multilevel data passing in Angular

Suppose you have a parent component A and inside of it you have some variable x. You would like to pass this variable to the child component B. Easy! Just use #Input annotation and call it a day. But what if B has another child component C? How would we pass x from A to C? I tried using the same approach to pass it from B to C, but it only passes the value undefined.
You can use a common service file which is data.service.ts file in this case. This service will be injected by both the parent and grand child. When component A which is grand parent here want to send a data it will call the deliverMsg method of the data service file. The component C which is grand child will listen to this change by injecting the same data.service
data.service.ts
// relevant imports
#Injectable()
export class DataService {
private message = new BehaviorSubject('default message');
portMessage = this.message.asObservable();
constructor() { }
deliverMsg(message: string) {
this.message.next(message)
}
}
parent.component.ts
//all relevant imports
#Component({
selector: 'app-parent-a',
template: 'html file url',
styleUrls: ['./sibling.component.css']
})
export class ParentComponent implements OnInit {
message:string;
constructor(private data: DataService) { }
ngOnInit() {
}
newMessage() {
this.data.deliverMsg("Hello from Grand Parent")
}
}
grandchild.component.ts
// all relevant imports
#Component({
selector: 'app-sibling',
template: 'template',
styleUrls: ['./sibling.component.css']
})
export class SiblingComponent implements OnInit {
message:string;
constructor(private data: DataService) { }
ngOnInit() {
this.data.portMessage.subscribe(message => this.message = message)
}
}
Alternatively you can also you NgRx

Interdependent component which need to communicate each other

I am in a situation like i have 5 interdependent component which need to communicate each other. For example if i click on a button A on all other 4 component need to listen to the click and alert something. The same way button in other component also listened by all other 4. Need a best solution on how to achieve this.
here is my code snippet
import { Component, OnInit } from '#angular/core';
import { CommonService } from 'broadcast-recive/service/common-service';
#Component({
selector: 'app-broadcaster',
templateUrl: './broadcaster.component.html',
styleUrls: ['./broadcaster.component.css']
})
export class BroadcasterComponent implements OnInit {
constructor(private commonservice: CommonService) { }
ngOnInit() {
}
broadCastMe(): void
{
this.commonservice.btnClickedInBroadCasterComponent((<HTMLButtonElement>event.target).id);
}
}
import { Component, OnInit } from '#angular/core';
import { CommonService } from 'broadcast-recive/service/common-service';
#Component({
selector: 'app-listener1',
templateUrl: './listener1.component.html',
styleUrls: ['./listener1.component.css']
})
export class Listener1Component implements OnInit {
constructor(private commonservice: CommonService) { }
ngOnInit() {
this.commonservice.clickStatusForBroadCastercomponentBtn.subscribe((id: string) => {
alert('alert from listner 1');
})
}
}
import { Component, OnInit } from '#angular/core';
import { CommonService } from 'broadcast-recive/service/common-service';
#Component({
selector: 'app-listener2',
templateUrl: './listener2.component.html',
styleUrls: ['./listener2.component.css']
})
export class Listener2Component implements OnInit {
constructor(private commonservice: CommonService) { }
ngOnInit() {
this.commonservice.clickStatusForBroadCastercomponentBtn.subscribe((id: string) => {
alert('from listner 2');
});
}
}
Here am always getting alert box "from listener 2 " , My requirement is its should trigger both the listener. Please help me refactoring the code. blow is my service where am using rx js for subscribing.
import {Subject} from 'rxjs/Subject';
import { Injectable } from '#angular/core';
#Injectable()
export class CommonService {
public clickStatusForBroadCastercomponentBtn = new Subject<string>();
public clickStatusForBcomponentBtn = new Subject<string>();
btnClickedInBroadCasterComponent(btnId: string): void {
this.clickStatusForBroadCastercomponentBtn.next(btnId);
}
btnClickedInComponentB(btnId: string): void {
this.clickStatusForBcomponentBtn.next(btnId);
}
}
You can do this using rxjs Subject declared in a service. Lets say, you have a service named AService:
import {BehaviorSubject} from 'rxjs/BehaviorSubject;
#Injectable()
export class AService {
public clickStatusForAcomponentBtn = new BehaviorSubject<string>('');
public clickStatusForBcomponentBtn = new BehaviorSubject<string>('');
btnClickedInComponentA(btnId: string): void {
this.clickStatusForAcomponentBtn.next(btnId);
}
btnClickedInComponentB(btnId: string): void {
this.clickStatusForAcomponentBtn.next(btnId);
}
}
Now, you can use this service in all your components those need to communicate with each other like this:
export class AComponent implement OnInit {
constructor(private aService: AService){}
ngOnInit(){
this.aService.clickStatusForBcomponentBtn .subscribe((clickedBtnId:string)=> {
// whenever button with id clickedBtnId clicked in Component B this observer
// will be get executed.So, do your necessary operation here.
}
}
btnClickListenerForA(event:Event){ /* in this component template you'll bind this listener with your button click event */
this.aService.btnClickedInComponentA((<HTMLButtonElement>event.target).id);
}
}
export class BComponent implement OnInit {
constructor(private aService: AService){}
ngOnInit(){
this.aService.clickStatusForAcomponentBtn .subscribe((clickedBtnId:string)=> {
// whenever button with id clickedBtnId clicked in Component A this observer
// will be get executed.So, do your necessary operation here.
}
}
btnClickListenerForB(event:Event){ /* in this component template you'll bind this listener with your button click event */
this.aService.btnClickedInComponentB((<HTMLButtonElement>event.target).id);
}
}
If you review the code, you'll understand two subjects are used to pass communication between two component. This way, you'll able to communicate between any number of components.
Thus, you can declare a rxjs subject for every button and for listening any button's click event you've to subscribe that buttons subject in other components where you want to listen that buttons event.
Hope this will guide you in a right direction.
You should use a shared service with a BehaviorSubject to emit any changes to any component listing to it please take a look at my answer Here I posted it like a few seconds ago on a similar question.

Angular 2 call a function in another component (Comp2) from the html of comp1

--- Component 1---------------
<div>
<li> Instance 2 </li>
However, the implementation of getFactsCount() is in another component. Should I use #output/ emitter or something?
----Component 2-----------
#component({
selector:'comp2'
templateUrl:'comp2.html'
})
export class Component2 implements OnInit{
getFactsCount(){
console.log("Function inside component2");
}
}
Correct Approach: You should either use an angular service or an event emitter.
To answer your question : In your component 2 call component 1 function as below:
let comp = new Component1();
let count = comp.getFactsCount();
You should put common logic in service something like:-
import { Injectable, Inject } from '#angular/core';
#Injectable()
export class MyService {
getFactsCount(): any {
//some logic here
}
}
Then in component constructor inject something like
#component({
selector:'comp1',
templateUrl:'comp1.html',
providers:[MyService]
})
export class Component1 implements OnInit{
constructor( private service : MyService ) {
}
getFactCount():any{
return this.service.getFactCount()
}
You can register your service globally (in app.module if you are using cli) also

Getting dependency from Injector manually inside a directive

I am trying to create a generic directive which will take a class type for rule validation and according to the rule in the class the directive will either show or hide an element.
This is my attempt so far.
PLUNKER Demo
myIf-Directive.ts
#Directive({
selector: '[myIf]'
})
export class MyIfDirective {
constructor(private _viewContainer: ViewContainerRef,
private _template: TemplateRef<Object>)
{ }
#Input() set myIf(rule: string) {
//rule class type will come as string
//how can I use string token to get dependency from injector?
//currently harcoded
//will the injector create new instance or pass on instance from parent?
let injector = ReflectiveInjector.resolveAndCreate([AdminOnly]);
let adminOnly : IRule = injector.get(AdminOnly);
let show = adminOnly.shouldShowElement();
show ? this.showItem() : this.hideItem();
}
private showItem() {
this._viewContainer.createEmbeddedView(this._template);
}
private hideItem() {
this._viewContainer.clear();
}
}
app-component.ts
#Component({
selector: 'my-app',
template: `
<div *myIf="'AdminOnly'">
<h2>Hello {{name}}</h2>
</div>
`,
})
export class App {
name:string;
constructor() {
this.name = 'Angular2'
}
}
But I am stuck in 2 places:
I keep getting the error No Provider for AuthService
I do not know how I can get the dependency from Injector using class name as string rather than the type
Any suggestion whether this is the right way to do it or where I am going wrong is highly appreciated.
You need to pass the parent injector like
export class MyIfDirective {
constructor(private injector:Injector, private _viewContainer: ViewContainerRef,
private _template: TemplateRef<Object>)
{ }
#Input() set myIf(rule: string) {
let resolvedProviders = ReflectiveInjector.resolve([AdminOnly]);
let childInjector = ReflectiveInjector.fromResolvedProviders(resolvedProviders, this.injector);
let adminOnly : IRule = childInjector.get(AdminOnly);
let show = adminOnly.shouldShowElement();
show ? this.showItem() : this.hideItem();
}
private showItem() {
this._viewContainer.createEmbeddedView(this._template);
}
private hideItem() {
this._viewContainer.clear();
}
}
See also Inject service with ReflectiveInjector without specifying all classes in the dependency tree
Just update for Angular version 10+:
From your service:
#Injectable({
providedIn: 'any'
})
export class AdminOnly { ... }
In your directive or a pure function, ...:
import { Injector } from '#angular/core';
...
const injector: Injector = Injector.create({
providers: [{provide: AdminOnly, deps: []}]
});
const adminOnly: AdminOnly = injector.get(AdminOnly);
let show = adminOnly.shouldShowElement();
...
See more

updating variable changes in components from a service with angular2

My app has a NameService which holds the name.
There are two child components of App, Navbar and TheContent which reference this service. Whenever the name changes in the service, i want it to update in both of the other components. How can i do this?
import {Component, Injectable} from 'angular2/core'
// Name Service
#Injectable()
class NameService {
name: any;
constructor() {
this.name = "Jack";
}
change(){
this.name = "Jane";
}
}
// The navbar
#Component({
selector: 'navbar',
template: '<div>This is the navbar, user name is {{name}}.</div>'
})
export class Navbar {
name: any;
constructor(nameService: NameService) {
this.name = nameService.name;
}
}
// The content area
#Component({
selector: 'thecontent',
template: '<div>This is the content area. Hello user {{name}}. <button (click)=changeMyName()>Change the name</button></div>'
})
export class TheContent {
name: any;
constructor(public nameService: NameService) {
this.name = nameService.name;
}
changeMyName() {
this.nameService.change();
console.log(this.nameService.name);
}
}
#Component({
selector: 'app',
providers: [NameService],
directives: [TheContent, Navbar],
template: '<navbar></navbar><thecontent></thecontent>'
})
export class App {
constructor(public nameService: NameService) {
}
}
Provide an event in the service and subscribe to it in the components:
#Injectable()
class NameService {
name: any;
// EventEmitter should not be used this way - only for `#Output()`s
//nameChange: EventEmitter<string> = new EventEmitter<string>();
nameChange: Subject<string> = new Subject<string>();
constructor() {
this.name = "Jack";
}
change(){
this.name = 'Jane';
this.nameChange.next(this.name);
}
}
export class SomeComponent {
constructor(private nameService: NameService) {
this.name = nameService.name;
this._subscription = nameService.nameChange.subscribe((value) => {
this.name = value;
});
}
ngOnDestroy() {
//prevent memory leak when component destroyed
this._subscription.unsubscribe();
}
}
See also
angular.io - COMPONENT INTERACTION - Parent and children communicate via a service
Since name in NameService is a primitive type, you'll get different instance in the service and your components. When you change name in NameService, the component properties still have the initial value and the binding doesn't work as expected.
You should apply the angular1 "dot rule" here and bind to a reference type. Change NameService to store an object that contains the name.
export interface Info {
name:string;
}
#Injectable()
class NameService {
info: Info = { name : "Jack" };
change(){
this.info.name = "Jane";
}
}
You can bind to this object and get updates to the name property automatically.
// The navbar
#Component({
selector: 'navbar',
template: '<div>This is the navbar, user name is {{info.name}}.</div>'
})
export class Navbar {
info: Info;
constructor(nameService: NameService) {
this.info = nameService.info;
}
}
I think that the solution provided by Günter is the best one.
That said, you must be aware that Angular2 services are singleton that take place into a tree of injectors. This means that:
if you define your service at the application level (within the second parameter of the bootstrap method), the instance can be share by all elements (components and service).
if you define your service at the component level (within the providers attribute), the instance will be specific to the component and its sub components.
For more details of such aspect, you can have a look at the "Hierarchical Dependency Injection" doc: https://angular.io/docs/ts/latest/guide/hierarchical-dependency-injection.html
Hope it helps you,
Thierry

Categories

Resources