【问题标题】:Angular 6 call function from 1 component to another but data not changed从一个组件到另一个组件的 Angular 6 调用函数,但数据未更改
【发布时间】:2018-08-30 05:20:50
【问题描述】:

我是 Angular 6 的新手。我有 header componentdashboard component

在我的header comp 中,我弹出通知列表,其中包含带有接受和删除选项的通知列表。

在我的dashboard component 中,我有已接受通知的列表。

如果我接受来自标题的新通知,则应在仪表板中更新列表。

在我的标题组件中,我包含了 flowwing

import { DashboardComponent } from '../../pages/dashboard/dashboard.component';

// 包含仪表板组件作为提供者

@Component({
  selector: 'app-siteheader',
  providers:[DashboardComponent ],
  templateUrl: './siteheader.component.html',
  styleUrls: ['./siteheader.component.css']
})

// 在名为dashcomp的构造函数中

 constructor( private dashcomp: DashboardComponent, private dashboardservice: DashboardService, private authenticationService: AuthenticationService) { }

// 通知接受动作

actionaccept(id){

    this.authenticationService.acceptaction(id)
            .subscribe(
                data => {  


// caled the dashboard function

                   this.loaddashboard();
                }
            );

  }

//通过使用这个函数调用仪表板组件的函数。

 public loaddashboard() {
        console.log('called');
        this.dashcomp.dolist('future'); 
      }

在仪表板组件中:

dolist(type) {
    console.log('dasss');
     this.dashservice.listengagement(type,this.page,this.limit)
            .subscribe(
                data => {    
                  console.log(data);
                   this.futureloader = false;
                   this.futurelist = data['result']; 
                   this.futuretotal = data['count'];

                }
            );
  }

在仪表板 html 中使用 ngfor 显示的结果

我的问题是::从标题中触发了仪表板功能。它显示控制台。但是仪表板中的输出没有改变。我有什么遗漏吗??

【问题讨论】:

  • 将 BehaviorSubject 与 Observable 一起使用
  • 您可以在服务中使用单例行为主体。在需要一致数据的任何地方更新并订阅它。 blog.angular-university.io/…

标签: angular typescript npm angular6


【解决方案1】:

您需要获取列表的 Observable,并在 html 中使用带有 ngFor 的异步管道来显示列表。此外,在标题组件中导入仪表板组件的方式也是不好的做法。更好的方法是为您的列表处理提供服务,并将服务注入两个组件中。

【讨论】:

  • 感谢您的回复。我是角度的新手。你知道这方面的任何工作演示吗?
  • 试试这个。 medium.com/dailyjs/…
【解决方案2】:

你可以使用 rxjs 主题

首先创建common.service.ts

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

@Injectable()
export class CommonService {

  subject$ = new Subject<any>();

}

然后从你的 header.component.ts 调用 next 方法来设置值,

constructor(private commonService: CommonService) { }

loaddashboard() {
    console.log('called');
    this.commonService.subject$.next('future');
  } 

并在dashboard.component.ts 订阅该事件

constructor(private commonService: CommonService) { }

  ngOnInit() {

    this.commonService.subject$.subscribe(data =>{
      console.log('response from header is => ',data);
    });
  }

这是Stackblitz 演示

【讨论】:

  • 我已经实现了上述步骤。仪表板中没有触发任何功能。这里调用 dolist(type) 函数的地方。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
  • 1970-01-01
  • 2017-07-13
  • 2020-05-02
  • 1970-01-01
  • 2018-11-30
  • 2019-01-27
相关资源
最近更新 更多