angular 2 subscribe shareService working twice or several times - javascript

I have a ShareService in angular 2,
******************************shareService*************************
import { BehaviorSubject , Subject} from 'rxjs/Rx';
import { Injectable } from '#angular/core';
#Injectable()
export class shareService {
isLogin$:BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
CheckUser = this.isLogin$.asObservable();
public isLogin (bool){
this.isLogin$.next(bool);
}
}
and its my another component and subscibe the CheckUser;
***********************another Component*******************************
_shareService.CheckUser.subscribe((val) =>{
*********all of this scope execute for several times just i have one another component and one next function*******
this.isLogin = val;
alert(val);
if(this.isLogin){
console.log("req req req");
this.MyBasket();
}
else if(this.ext.CheckLocalStorage("ShopItems")){
this.ShopItems = JSON.parse(localStorage.getItem("ShopItems"));
setTimeout(() => {
_shareService.sendShopItems(this.ShopItems);
},100);
}
});
my problem is i execute once this.isLogin$.next(bool) but subscribe function execute twice or several times !!!! my basket function is an xhr request this means when user loged in i get the several request to server!!!i cant fix it...i dont know this problem is for angular 2 or not,Anyone have this problem??
last a few days i Involved in this problem!

The problem is that your shareService is getting multiple instances.
One of the solutions is forcing the service to be a singleton.
Something like this should work:
import { provide, Injectable } from '#angular/core';
#Injectable()
export class shareService {
private static instance: shareService = null;
// Return the instance of the service
public static getInstance(/*Constructor args*/): shareService {
if (shareService.instance === null) {
shareService.instance = new shareService(/*Constructor args*/);
}
return shareService.instance;
}
constructor(/*Constructor args*/) {}
}
export const SHARE_SERVICE_PROVIDER = [
provide(shareService, {
deps: [/*Constructor args dependencies*/],
useFactory: (/*Constructor args*/): shareService => {
return shareService.getInstance(/*Constructor args*/);
}
})
];
Everything that is required on your current constructor should be placed where it says constructor args
Now on your components you use the service like this:
#Component({
providers: [SHARE_SERVICE_PROVIDER]
})
And then you can call it like you usually do.
Another solution would be injecting your current service on the main component of the app. See here for more info.

The problem is that the service is singleton and the component subscribe to it each time it created or (I don't see the full code) at the point the
_shareService.CheckUser.subscribe
is placed , so CheckUser should be a method that returns an Observable . if you have plunkr I can edit it .
Another semantic problem is that the observable should end with $ and not the BehaviorSubject.

Related

Angular. How to switch component depending on service's actions

Lets say I have 2 components, aComponent and bComponent. I have them redered inside the AppComponent
<app-a>
<app-b>
And I have service myService that has method .trigger().
What I want is to show only aComponent, but whenever I call myService.trigger() from another part of code, it would switch and show bComponent. That's perfect implementation that I can't reach.
Question is: Is it possible to do so? And if not what is the best closest solution.
The only working solution I got:
I added .trigger() inside AppComponent
export class AppComponent {
title = 'spa';
show: boolean = false;
trigger() {
this.show = true;
}
}
And rendered components like so:
<div *ngIf="!show; else show">
<app-a></app-a>
</div>
<ng-template #show>
<app-b></app-b>
</ng-template>
Then whenever I want to trigger switching, I add instance of the app to the constructor and call it's method:
export class AnotherComponent implements OnInit {
constructor(
private app: AppComponent
) {}
ngOnInit(): void {
this.app.trigger();
}
}
Even though it's working pretty good, I myself see that it's a dirty solution. Components are not intended to be used inside another components, but Services are.
You can use Subject from rxjs library for that.
In your service file:
// a-service.service.ts
import { Injectable } from '#angular/core';
import { Subject } from 'rxjs';
#Injectable({ providedIn: 'root' })
export class AService {
private subject = new Subject<any>();
trigger(state: boolean) {
this.subject.next(state);
}
getTrigger(): Subject<any> {
return this.subject;
}
}
and in your AppComponent:
// app.component.ts
...
private show = false;
constructor (private aService: AService) { }
ngOnInit() {
this.aService.getTrigger().subscribe(state => {
this.show = state;
});
}
the template can be as you provided - it's fine:
<div *ngIf="!show; else show">
<app-a></app-a>
</div>
<ng-template #show>
<app-b></app-b>
</ng-template>
And if you want to trigger from another component, you do it like this:
// another.component.ts
...
constructor (private aService: AService) { }
ngOnInit() {
this.aService.trigger(true);
}
One way to communicate between different components and services which aren't directly related, is via 'Subjects'.
You can try to create a subject and pass in values to it from myService.trigger(). And you can subscribe to that subject from whichever component you want to access that trigger data.

angular 8 how to get and set values and access the value from any page? [duplicate]

This question already has an answer here:
How to share data between components using a service properly?
(1 answer)
Closed 2 years ago.
hello i am using angular 8 and i would like to know how can i access the set value in any page ?
my code
class.ts
export class testClass {
get test():string{
return this.sexe;
}
set test(val:string){
this.sexe = val;
}
}
in clild.ts
import { testClass } from '../class';
export class Child{
constructor (private test:testClass){}
test (){
this.test.test = "hello";
}
in parent.js
import { testClass } from '../class';
export class Parent{
constructor (private test:testClass){}
test (){
console.log(test.test);
}
}
in app.module.ts
import { testClass } from '../class';
providers: [testClass],
what am i doing wrang to get "test undifined" in parent.js
Not to sure what you mean by setting and getting the value in any page? I'm assuming you mean component?
If so I'd use a service like so
#Injectable({
providedIn: 'root'
})
export class ExampleService{
private _value: any;
private _valueObs$ = new BehaviorSubject(null);
set setValue(newValue: any): void{
this._value = newValue;
}
get getNewValue(): any{
return this._value;
}
set setObservableValue(newValue: any): void{
this._valueObs$.next(newValue)
}
get getNewObservableValue(): any{
return this._valueObs$;
}
}
There are two approaches in the above method, the first is a pretty standard set and get, the second is utilising something known as a Subject, I'll touch on the difference in the next section.
To then use this service in any component
#Component({
selector: 'example',
})
export class ExampleComponent implements OnInit {
newValue: any;
constructor(private readonly exampleService: ExampleService
) { }
ngOnInit(): void {
this.getObservableExampleValue();
}
getExampleServiceValue(): any {
this.exampleService.getNewValue;
}
setExampleServiceNewValue(value: any): void {
this.exampleService.setNewValue = value;
}
getObservableExampleValue() {
this.exampleService.getNewObservableValue.subscribe((newObsValue) => {
this.newValue = newObsValue
})
}
setObservableExampleValue(value: any): void{
this.exampleService.setObservableValue(value);
}
ngOnDestroy(){
this.exampleService.getNewObservableValue.unsubscribe();
}
}
So I wont go into detail on the standard setValue & getNewValue, you can invoke them how you see fit.
Now the second approach is great if you want several components to be aware of a particular value at one time, so lets say we set the _valueObs$ with the setObservableValue method, and we have used this service in 5 different components, all 5 of those components will receive that value, very handy right?
Now you'll notice it's important that we actually invoke the getNewObservableValue so we can open the stream, normally you'd do this on the ngOnInit so the components template/code can have access to the value, assuming your looking to use the value straight away, otherwise you can invoke it at a later date, the way subscribing/observable's work is a bit like a tap.
Imagine you have a tap, and you turn it on - Known as subscribing
this.exampleService.getNewObservableValue.subscribe((newObsValue) => {
this.newValue = newObsValue
})
Well the tap is turned on and now emits a stream of water or again in this case a stream of data, so every time you set a new value, the new piece of data will come through that stream and will automatically update the this.newValue within your component.
But it's also important to turn the tap off! We don't want to be wasting water when we are done using it, this is when we unsubscribe when the component is no longer being used so
ngOnDestroy(){
this.exampleService.getNewObservableValue.unsubscribe();
}
This is to prevent what is known as a memory leak, which is beyond the scope of this answer, know to learn more about Rxjs I'd read some documentation - https://www.learnrxjs.io/ or watch some youtube videos there are plenty of tutorials out there!
Hopefully I've explained comprehensively enough if not feel free to comment.
You have to use a service.
The services are initialized when the app starts, and remain so until it stops. Passing a value through a service allows you to access it anywhere you call the service.
So if you had the following:
#Injectable()
export class ExampleService {
public varIWant: string = 'I wan't to use this anywhere.'
}
You can access it in your components, by doing:
import { ExampleService } from '../my/path/to/service'
export class Parent {
constructor(private exampleService: ExampleService) { }
public setVarAsLocal: string = this.exampleService.varIWant;
public changeServiceVariable() {
this.setVarAsLocal = 'New Value For String';
this.exampleService.varIWant = this.setVarAsLocal;
}
}
And that's it. As long as the instance is running the value will hold;

How to send array in router navigate?

Searched for a solution in other questions but nothing helped me..
I wish to redirect to url like,
this.router.navigateByUrl('/products');
In which i need to pass the array and need to get it it in the component which has the active link products using skip location change without showing anything in url.
Array will be like,
products = [{"id":1,"name":"Product One","id":2,"name":"Product Three","id":3,"name":"Product Six"}]
I need to pass this entire array in router link and need to retrieve it in another component (products) active link using skipLocation Change true..
Tried with sharedService but i am getting issue of data loading at right point of time and hence i decided to use via router link..
If this is not a good approach, kindly suggest other alternative without using sharedservice..
You can use Angular Services for a large data.
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
#Injectable()
export class ExampleService {
private subject = new Subject<any>();
updateRouteData(data) {
this.subject.next(data);
}
routeData(): Observable<any> {
return this.subject.asObservable();
}
}
In your components;
For set route data;
import { ExampleService } from '/example.service'
export class ComponentOne{
constructor(private exampleService:ExampleService){
this.exampleService.updateRouteData(data)
}
You can pass data like;
import { ExampleService } from '/example.service'
export class ComponentTwo{
constructor(private exampleService:ExampleService){
this.exampleService.routeData().subscribe(data => {
console.log(data)
})
}

Angular Material Data Table component is not live streaming

I'm using Angular Material Data Table in my project. The table is rendering with data
My problem is that I can't update automatically the view when I add new data to the database, every time I should refresh my page.
According to Cdk-table and after reading this tutorial I tried to add live data streaming that to table:
Here's my logique :
import { Component, OnInit } from "#angular/core";
import { MatTableDataSource } from "#angular/material";
import { AjoutprojService } from "../ajoutproj.service";
import { NouveauProjet } from "../models/nouveau-projet";
import { Observable } from "rxjs/Observable";
import 'rxjs/add/observable/merge';
import { DataSource } from "#angular/cdk/collections";
#Component({
selector: "app-liste-projets",
templateUrl: "./liste-projets.component.html",
styleUrls: ["./liste-projets.component.css"]
})
export class ListeProjetsComponent implements OnInit {
constructor( private ajoutProj: AjoutprojService ) {}
nouveauProjet: NouveauProjet[];
nouveauProjet2: NouveauProjet[];
stateExression: string = "inactive";
ngOnInit() {}
displayedColumns = ["Nom projet", "Lead Projet", "effectif"];
dataSource = new UserDataSource(this.ajoutProj);
applyFilter(filterValue: string) {
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
//this.dataSource.filter = filterValue;
}
}
export class UserDataSource extends DataSource<any> {
constructor(private ajoutProj: AjoutprojService) {
super();
}
/*returns an observable that emits an array of data.
Whenever the data source emits data to this stream, the table will render an update.*/
connect(): Observable<NouveauProjet[]> {
return this.ajoutProj.getAllProj();
}
disconnect() {}
}
Here's my service
getAllProj(): Observable<NouveauProjet[]> {
return this.http.get<NouveauProjet[]>(
"http://127.0.0.1:8081/api/proj/projets"
);
}
ajoutProj.getAllProj() service is getting right data. but view is not live updating.
HttpClient doesn't stream. You're getting your data only once.
First you'd need a realtime database / backend solution, then you need to connect to that via websocket and listen to changes in the database.
Some frameworks / libraries that I like and package both the client- and serverside of the equation, and make the whole thing a lot easier:
Fireloop - built on top of Loopback 3 on nodejs, provides Angular SDK creation, ie. same models and APIs on client as on server. Typescript, Observables all the way. It's just awesome.
Firebase - "backendless", totally different way of thinking about a "server" from any REST scheme you might be used to.
Meteor - a monolithic framework, probably also very far from what you're used to.
Of course there's always another (very inefficient) way: Poll your DB every X seconds for changes.
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/switchMap';
export class UserDataSource extends DataSource<any> {
constructor(private ajoutProj: AjoutprojService) {
super();
}
connect(): Observable<NouveauProjet[]> {
const initialDelay = 0; // Time to wait before first poll, after the table has connected to this DataSource
const period = 10000; // Polling period in milliseconds
return Observable.timer(initialDelay, period)
.switchMap(() => this.ajoutProj.getAllProj());
}
disconnect() {}
}

NodeJS, Angular 2 | Executing method on Observable next

I'm currently getting started with Angular 2 and got stuck on something probably pretty simple:
I have a shared service chatMessageService.ts:
import { Injectable } from '#angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
#Injectable()
export class ChatMessageService {
private messageList = new BehaviorSubject<string>("");
currentMessage = this.messageList.asObservable();
constructor() {
}
public addMessage(msg:string) {
this.messageList.next(msg) }
}
The service is imported by two components, one that calls it's addMessage function to add the message to the Observable and then my chatComponent.ts looks like this (shortened fpr convinience):
import { Component } from '#angular/core';
import { Message } from './message';
import { ChatMessageService } from './chatMessage.service';
#Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.css']
})
export class ChatComponent {
conversation: Message[] = [];
//.....
constructor(private chatMessageService: ChatMessageService) { }
addUserMessage(message) {
this.conversation.push({
content: message
});
}
ngOnInit() {
this.chatMessageService.currentMessage.subscribe(message => {this.addUserMessage(message);} )
}
}
My crisis arises at that last subscripion part. When I replace
{this.addUserMessage(message);}
with
{console.log(message)}
the message is printed out perfectly fine. If I call the addUserMessage()-method manually it works just fine. But when I call the method right there, with the message as argument, nothing happens. The method isn't even executed?
Thankful for your insights!
It looks like you need some buffering in the service.
Instead of BehaviorSubject, try
private messageList = new ReplaySubject<string>(10);
See working example: Plunker

Categories