Evan Zou

Welcome to my blog.

Javascript follower.


Hi, I am Evan, nice to meet you all.

Angular2+ 如何向不关联组件传入数据

关键词 Angular2+

前言

众所周知,Angular2+向子组件传递数据用@Input(), 子组件向父组件传递数据用@Output()。现在因为项目需求,需要在Angular2+的不关联组建中传递数据,本文详细介绍了具体步骤和代码。

步骤

1.在service文件添加如下代码

private idSubject: BehaviorSubject<number> = new BehaviorSubject<number>(null);
public id = this.idSubject.asObservable();

setCurrentId(id: number = null) {
  this.idSubject.next(id);
}

2.在需要传值的地方call setCurrentId

this.service.setCurrentId(xx) // xx代表要传入的id

3.在需要调用id的地方添加如下代码

private ngUnsubscribe = new Subject<void>();
...
 ngOnInit(): void {
    this.service.id
      .pipe(takeUntil(this.ngUnsubscribe))
      .subscribe((id) => {
        if(id) {
         ....
        }
      });
  }
  

后言

希望本文会对你有所帮助,如果有什么问题,可在下方留言沟通

最近的文章

如何发起参数里面有句号的请求

关键词 API前言在项目过程中,在发送WS请求的时候,需要传递一个带句号的参数,本文介绍了如何发起这样的请求。步骤在参数后加’/'用来转义,详细代码如下{% highlight ruby %} getCount(cwsLogin: string): Observable<ICount[]> { return this.apiService .get(/count/${cwsLogin}\/) // 注:\反斜线用来转义 .pipe( ma...…

API继续阅读
更早的文章

Angular13 如何修改项目baseUrl

关键词 Angular13前言因为项目需求,需要修改项目的baseUrl,本文详细介绍了具体步骤和代码。步骤在文件中主要需要添加以下代码 index.html<head> ... <base href="/test"></head> package.json"scripts" :{ ... prod": "npm run icons && npm run wbv && ng build --configurat...…

Angular2+继续阅读