angular - Angular 6 - 无法使用主题订阅消息
问题描述
我正在尝试在 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();
}
}
解决方案
您在 3 个不同的地方提供服务,一次是在根目录下,一次是在每个组件上......从组件中的提供程序数组中删除服务,这将起作用。
您提供服务的每个地方都会将该服务的新副本提供给注入组件树该部分的任何组件。有时这是需要的,有时则不是。在这种情况下,它似乎不是你想要的。如果您确实想要多个独立的结果/过滤器组件不共享一个服务,您可能必须重新考虑您的页面结构或创建一些封装组件或指令来提供服务。
推荐阅读
- python - 从不包含数字的熊猫中删除行
- mongodb - 返回突变结果的正确方法?(GraphQL 与 Apollo 和 Mongoose
- javascript - 为什么触发 onFocus 时我的锚元素的轮廓没有出现?
- java - 无法找到持久性:com.package.model.Bus
- node.js - 创建推送通知的最佳和最简单的方法
- java - 由 postgresql plpython3u 调用的 kitchen.bat:java.lang.NullPointerException
- javascript - 尝试导入错误:“FetchXmlHttpFactory”未从“@firebase/webchannel-wrapper”导出(导入为“v”)
- jquery - 使用 laravel 和 ajax 切换自定义
- javascript - JavaScript 干扰 CSS 悬停动画
- angular - 在 Angular ngx-google-analytics 中跟踪电子商务