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
521 views
in Technique[技术] by (71.8m points)

angular11 - Angular 11 share data between unrelated components which a service

I am using Angular 11 and I have lots of methods in componentB (to call it one way)

I now have to make the calls to lots of methods that live in componentB from componentA.

I know that I could move all the methods to a service but in this case it would be a lot of work and I only need a fast workaround.

So I would like to keep componentB how it is and be able to call it's methods from componentA.

componentA and componentB are not releated.

Is there a workaround to do this without having to move the methods out of componentB?

question from:https://stackoverflow.com/questions/66060170/angular-11-share-data-between-unrelated-components-which-a-service

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

1 Reply

0 votes
by (71.8m points)

You can do it via service, which will be injected in both components Service could be like this one

@Injectable()
class MyDataService implements IMyDataService  {
 
    private whenMessageRecieved$: Subject<MyDataType> =
        new ReplaySubject(1);
 
    constructor(
    ) {
    }
 
    public notify(someData: MyDataType): void {
        this.whenMessageRecieved$.next(someData);
    }
 
    public whenMessageRecieved(): Observable<MyDataType> {
        return this.whenMessageRecieved$.asObservable();
    }
}

ComponentB should subscribe to whenMessageRecieved() and componentA should call notify with strict params. In nearest future this service will help you migrate methods from componentB

But still - it would be better to store common logic somewhere else, not in componentB


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

...