Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

javascript - How to pass a value from one component to another component Angular 2 (No parent child relationship)

Hi i have two components, component1 and component2. And i have a value, lets say x, and i want to pass the value to one of my component in my app, both have no parent-child or any relationship each other. How can i get the value x in component2 which is been set or created in component1? I know i can use local storage to set the value and get anywhere. Other than that is there any other way to do this? Sorry am new to Angular. Any idea guys? Thanks in advance. currently what i have done in my component1:

window.localStorage.setItem('myVal', JSON.stringify(x));

and in my component2:

let getmyVal: any = JSON.parse(localStorage.getItem("myVal"));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since there is no relationship between the components, the easiest approach is to go for a publisher-subscriber model. Any component can publish any message, and any other component can subscribe to the said message, using the Observable.

Here is a sample Alert Service we created in one of our application

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class AlertService {
    private subject = new Subject<any>();
        
    constructor() {
    }

    alert(alertType: string, objData: any) {
        this.subject.next({ type: alertType, data: objData });
    }

    getMessage(): Observable<any> {
        return this.subject.asObservable();
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...