如果您想在组件之间进行通信,您可以使用主题轻松完成。
对于您提到的示例,您有 3 个组件 A、B、C,那么如果您想将 A 组件中的数据获取到 C 组件,您必须首先提供服务
前任-
export class DatapassAtoCService{
private messageCommand = new Subject<string>();
Data$ = this.messageCommand.asObservable();
invokeMessage(msg: string) {
this.messageCommand.next(msg);
}
}
在此示例中,我传递值 msg(它是组件 A 中的类型字符串)来服务此服务使用一个可观察的主题,并且它发出已在服务中订阅此方法的值,如下所示。
import { Component, OnInit } from '@angular/core';
import { DatapassAtoCService} from '../services/message.service';
@Component({
selector: 'app-component-one',
templateUrl: './component-one.component.html',
styleUrls: ['./component-one.component.css']
})
export class Acomponent implements OnInit {
constructor(private DataService: DatapassAtoCService) { }
ngOnInit() {
}
string msg =This is pass to service;
yourActionMethod() {
this.DataService.invokeMessage(msg );
}
}
然后我们可以在 C 组件中订阅该服务,然后发送该 msg 值
import { Component, OnInit, OnDestroy } from '@angular/core';
import { DatapassAtoCService} from '../services/message.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-component-two',
templateUrl: './component-two.component.html',
styleUrls: ['./component-two.component.css']
})
export class CComponent implements OnInit, OnDestroy {
messageSubscription: Subscription;
message: string;
constructor(private Dataservice: DatapassAtoCService) { }
ngOnInit() {
this.subscribeToMessageEvents();
}
ngOnDestroy(): void {
this.Dataservice.unsubscribe();
}
subscribeToMessageEvents() {
this.messageSubscription = this.Dataservice.Data$.subscribe(
(msg: string) => {
this.message = msg;
}
);
}
}
因此,正如上面代码中提到的,我们可以使用 Ccomponent 中的 messageSubscription 获取 Acomponent msg 值