我正在尝试在 2 个组件之间进行通信。过滤器组件正在尝试通过服务 http-service 向结果组件发送消息。
我能够向服务 http-service 发送消息,但即使我订阅了也无法在结果服务中接收消息。这是代码
视图.module.ts
@NgModule({
declarations: [FilterComponent, ResultComponent],
imports: [
CommonModule,
FormsModule,
AgGridModule.withComponents(
[]
)
})
http服务
import{Injectable}from'@angular/core';
import {Observable }from 'rxjs';
import {of }from 'rxjs';
import {Subject}from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class HttpServiceService {
private subject = new Subject<any>();
sendMessage(message: string) {
this.subject.next({ text: message });
}
clearAnswers() {
this.subject.next();
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
过滤器组件.ts
import{Component, OnInit}from '@angular/core';
import {HttpServiceService}from '../http-service.service';
@Component({
selector: 'app-filter',
templateUrl: './filter.component.html',
styleUrls: ['./filter.component.css'],
providers: [ HttpServiceService ]
})
export class FilterComponent implements OnInit {
constructor(private httpService:HttpServiceService) { }
onFormSubmit() {
this.httpService.sendMessage('Form submitted');
}
}
结果.component.ts
import{Component, OnDestroy}from '@angular/core';
import {Subscription}from 'rxjs';
import {GridOptions}from "ag-grid-community";
import {HttpServiceService}from '../http-service.service';
@Component({
selector: 'app-result',
templateUrl: './result.component.html',
styleUrls: ['./result.component.css'],
providers: [ HttpServiceService ]
})
export class ResultComponent implements OnInit {
message : any;
subscription: Subscription;
constructor(private httpService: HttpServiceService) {
// subscribe to home component messages
this.subscription = this.httpService.getMessage().subscribe(message => {console.log(message); });
}
ngOnDestroy() {
// unsubscribe to ensure no memory leaks
this.subscription.unsubscribe();
}
}