【问题标题】:Angular 4 Reload header component from separate componentAngular 4从单独的组件重新加载标题组件
【发布时间】:2018-12-24 07:47:28
【问题描述】:

我有一个函数,它需要一个单独的标题组件在使用时刷新。

Foo 组件 (需要重新加载头部组件)

handleTimeListChange(value) {
    this.cp = value.
    localStorage.setItem('cp', this.cp);

    //reload header.component
  }

结果应该是使用时间handleTimeListChange时调用会重新加载(header.component)

【问题讨论】:

  • 为什么要重新加载 header.component 有没有原因?
  • 我在标头中有一些数据将采用新的 setItem 并刷新
  • 目前如果有新数据,标题不会反映在 ui 上吧?
  • 如果可能,请考虑提供Minimal, Complete, and Verifiable example,以便我们可以在“真实”上下文中看到问题。也许是stackblitz.com
  • 正确,但如果我可以重新加载组件,它将能够获取新设置的数据。 foo.component 有 handletimelistchange 并且 header.component 需要在设置该项目时重新加载。

标签: angular


【解决方案1】:

对于这个问题,你可以像这样使用 rxjs SubjectBehaviour.make random service

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

    @Injectable()
    export class RandomService {

      private msgsource = new BehaviorSubject<string>('this is the default');
      telecast = this.msgsource.asObservable();

      constructor() { }

      editMsg(newmsg) {
        this.msgsource.next(newmsg);
      }

    }

您要从中发送数据的组件,声明该服务 方法并将日期发送到该方法,并且无论何时调用该服务方法,该数据都将反映它们。

      import { Component, OnInit, Input } from '@angular/core';
        import { RandomService } from '../random.service';

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

          @Input('incomingmsg') newrandmsg: string;

          message: string;
          editedmsg: string;

          constructor(private someserv: RandomService) { }

          ngOnInit() {
          }

          editthemsg() {
            this.someserv.editMsg(this.editedmsg);
          }

        }

现在将该数据接收到 ngOnInit 中的标头组件,该组件将检测该服务方法中的任何值更改。

标题组件

ngOnInit() {
        this.someserv.telecast.subscribe(message => this.message = message);
      }

当任何更改出现在随机服务下时,它会检测到该数据并将其显示给标题组件。

【讨论】:

    【解决方案2】:

    您可以使用BehaviorSubject 在整个应用程序的不同组件之间进行通信。您可以定义一个包含 BehaviorSubject 的数据共享服务,您可以订阅和发出更改。

    看到这个答案:https://stackoverflow.com/a/46049546/4899523

    【讨论】:

      猜你喜欢
      • 2018-06-03
      • 2018-12-21
      • 2018-06-01
      • 1970-01-01
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      • 2020-08-08
      • 2018-08-13
      相关资源
      最近更新 更多