我建议最好的方法是使用 rxjs 主题。您可以在模态对话框组件或其他任何组件之间传递数据。像这样在您的服务中创建新的 rxjs 主题
import { Subject } from 'rxjs/Subject';
@Injectable()
export class MyService {
myNewSubject = new Subject<any>();
informDataChanges(passyourobject){
this.myNewSubject.next(passyourobject);
}
}
当您的组件发生更改或您想将数据传递给另一个组件时,只需从您的组件调用此服务函数并将数据作为参数传递给此函数。你可以用这样的东西来做到这一点
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-some',
templateUrl: './some.component.html',
styleUrls: ['./some.component.css']
})
export class SomeComponent implements OnInit {
constructor( private myService: MyService) { }
someFunction(){
this.myService.informLogout('somedata');//Passing data to service here
}
ngOnInit() {
}
}
现在您需要做的就是在另一个组件中订阅该数据。重要的主题会持续关注它的任何变化,并且数据将是连续的流并且它会被自动订阅。所以最好在构造函数中订阅主题,更改会立即反映在该组件中。
你用这样的东西来做
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-another',
templateUrl: './another.component.html',
styleUrls: ['./another.component.css']
})
export class AnotherComponent implements OnInit {
constructor( private myService: MyService) {
this.myService.myNewSubject.subscribe(data=>{
console.log(data);
})
}
通过这种方式,您可以轻松地在任何组件之间传递数据。