1

我正在尝试在 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();
    }
}
4

1 回答 1

2

您在 3 个不同的地方提供服务,一次是在根目录下,一次是在每个组件上......从组件中的提供程序数组中删除服务,这将起作用。

您提供服务的每个地方都会将该服务的新副本提供给注入组件树该部分的任何组件。有时这是需要的,有时则不是。在这种情况下,它似乎不是你想要的。如果您确实想要多个独立的结果/过滤器组件不共享一个服务,您可能必须重新考虑您的页面结构或创建一些封装组件或指令来提供服务。

于 2019-01-12T18:36:09.143 回答