angular event服务,不同组件间参数传递
  87GpfEheVoVF 2023年11月02日 27 0

利用Angular Event在不同组件之间传递数据

为了实现在Angular不同Component之间相互传递数据,可以使用Event分发的思路来实现。
使用事件实现在不同组件之前传递数据的思路如下:

  • 定义一个服务,用来实现事件的发布和订阅方法。
  • 组件A注入事件服务的依赖,将自己要传递数据的数据以事件的形式发布出去。
  • 组件B注入事件服务的依赖,并订阅相关事件。

定义一个服务

在终端输入
ng g service event
Angular会自动在项目的app目录下生成 event.service.tsevent.service.spec.ts 两个文件。
我们在 event.service.ts 文件中完成相关业务代码即可。
例如,我们在改服务中实现发布事件和订阅事件的方法:

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

// 使用事件实现在不同组件之前传递数据的思路

@Injectable({
    providedIn: 'root'
})
export class EventService {
    // 构建Subject的实例,用来完成事件的发布和订阅
    private subject = new Subject < any > ();
    constructor() {}
    publish(value: any, err: any) {
        if (value !== undefined) {
            // 将新的事件放入next队列中
            this.subject.next(value);
        }
        if (err !== undefined) {
            // 将错误放入error队列
            this.subject.error(err);
        }
        // 表示当前事件结束
        this.subject.complete();
    }

    subcribe(handler: {
      next: (value) => void,
      error: (err) => void,
      complete: () => void
    }) {
        this.subject.asObservable().subscribe(handler);
    }
}

最后,为了能让我们定义的服务能够被注入到其他组件中,我们还需要在app.modules.ts文件中注册我们的服务:

import { EventService } from './service/event.service';

@NgModule({
  declarations: [],
  imports: [],
  providers: [EventService],
  bootstrap: [AppComponent]
})
export class AppModule { }

利用EventService在不同组件间传递数据

假定组件A中的数据需要传递到组件B中,这里的数据可以是事件、文本内容、状态改变等等东西。 则在组件A中,我们可以发布一个事件,组件B订阅该事件即可。

在组件A中发布事件

import { EventService } from '../../service/event.service';

export class AComponent implements OnInit {
  constructor(
    private eventS: EventService
  ) { }
  ngOnInit() {
  }
  someThingChanged(data) {
    // 发布事件
    this.eventS.publish({
      // 可以定义一个事件类型,实现多个不同类型事件的发布
      type: 'run finished',
      // 可以携带任何数据,并通过事件发布出去
      data: {'close': true},
      ohter: 'ohter msg'
    },'error');
  }
}

在组件B中订阅事件

import { EventService } from '../../service/event.service';

export BComponent implements OnInit {
  constructor(
    private eventS: EventService
  ) { }
  ngOnInit() {
    // 在ngOnInit,完成事件订阅
      this.eventS.subcribe({
        next: value => {
          // do something with value
          // console.log('next value: ' ,value)
          if (value.data.close == true) {
            this.isSpinning = false;
          }
        },
        error: err => {
          // handle err
        },
        complete: () => {
          // handle complete
          // console.log('complete')
        }
      })
  }
}

参考

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  gBkHYLY8jvYd   2023年12月09日   30   0   0 cii++数据
87GpfEheVoVF