【问题标题】:Angular - How to Subscribe Data from Component to ComponentAngular - 如何从组件订阅数据到组件
【发布时间】:2020-04-14 09:47:59
【问题描述】:

我正在尝试从组件订阅数据。 不知何故,它现在不起作用,希望任何人都可以找出原因......

app.component.html

<app-sample1></app-sample1>
<p></p>
<app-sample2></app-sample2>

sample1.component.html

<div class="main">
    <p>Sample1 !</p>
    Subsribed Title from Sample 2:
    <h3> {{titleFromSample2}}</h3>
</div>

sample2.component.html

<div class="main">
    <p>Sample2 !</p>
    <input type="text" #title (input)="change(title.value)">
</div>

sample.service.ts / sample1.component.ts / sample2.component.ts

在 Sample2 输入框中插入文本值时, sample2.componet.ts 中的 'change' 方法实现得很好。

但是 sample1.component.ts 和 sample1.component.html 的 titleFromSample2 值没有改变。

我找不到问题所在....

【问题讨论】:

  • 您是否有机会查看组件交互指南:angular.io/guide/component-interaction?它有一些适用于不同沟通策略的秘诀,将是一个很好的起点。此外,您还没有展示 titleFromSample2 是如何设置或提供给组件 1 的。
  • 好吧..我检查了链接和Angular官方文档,但找不到与我匹配的案例...

标签: angular rxjs


【解决方案1】:

那是因为您从getTitle 返回一个Observable,它本质上是单播。这意味着,它不会对SampleServicetitle 属性值的变化做出反应。

要使其多播,您必须改用SubjectBehaviorSubject

类似这样的:

import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';

@Injectable()
export class SampleService {

  private title: BehaviorSubject<string> = new BehaviorSubject<string>(null);

  constructor() { }

  setTitle(value: string) {
    this.title.next(value);
  }

  getTitle(): Observable<string> {
    return this.title.asObservable();
  }

}

此外,由于这将随着时间的推移发出多个值,并且当它们随着时间的推移发出多个值时,不建议subscribeObservables,您应该在模板中使用async 管道.

所以你的组件应该是这样的:

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { SampleService } from '../sample.service';

@Component({
  selector: 'app-sample1',
  templateUrl: './sample1.component.html',
  styleUrls: ['./sample1.component.css']
})
export class Sample1Component implements OnInit {

  titleFromSample2$: Observable<string>;

  constructor(private sampleService: SampleService) { }

  ngOnInit() {
    this.titleFromSample2$ = this.sampleService.getTitle();
  }

}

然后在模板中:

<div class="main">
    <p>Sample1 !</p>
    Subsribed Title from Sample 2:
    <h3> {{titleFromSample2$ | async}}</h3>
</div>

这里有一个Working Demo 供您参考。

【讨论】:

  • 谢谢!!您所解释的一切都非常清楚易懂。代码就像魅力一样工作:)
【解决方案2】:

问题在于 SampleService 存储了标题值,但它没有发出新值。将title改为title = new BehaviorSubject('');

然后在 setTitle:

setTitle(value: string) {
  this.title.next(value);
}

应该这样做。

【讨论】:

    猜你喜欢
    • 2021-12-14
    • 2019-01-25
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 2018-03-15
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多