组件之间的通讯Angular9.1.10

时间:2020-07-31 20:19:22

标签: angular

我在组件之间的通信上有问题。

组件A:此组件的形式是将信息发送到API并在我有响应时等待响应,然后更改为组件B并绘制响应

组件B:此组件从服务器获取响应

我尝试使用eventemmiter并通过这种方式使用服务中的var

服务

@Injectable()
export class ProjectService{
    public url:string;
    public report: string;
    @Output() change: EventEmitter<string>;
    

    constructor(
        private http:HttpClient
    ) {
        this.change =   new EventEmitter();
        this.url = Global.url
    }
    change_data(data){        
      this.report= data;
      this.change.emit(data) 
    }

A组分

onSubmit(form){ 

console.log("send")
this.projectService.getReport(this.project).subscribe(data=>{
  
 this.projectService.change_data("change");
  
  console.log("proyecto",this.projectService.report)
  
  this._router.navigate(['/reporte'])      
}, err=>{
  console.error("error",err)
});

}

组件B

ngOnInit() {
    this.projectService.change.subscribe(data=>{
      this.test = data;
    })
    console.log("report"+ this.test);
    this.test = this.projectService.report;



  }

此刻不使用服务器的响应,因为我正在测试此问题

1 个答案:

答案 0 :(得分:0)

对服务进行一些调整:

change = BehaviorSubject(null);
...
this.change.next(data);

1:服务中的@Output()没有用。它什么也没做,所以我删除了它

2:change更改为BehaviorSubject-棘手的主题,您在订阅时会获得最后一个值。仅使用emit数据并丢失该值后您就订阅了EventEmitter。

3:接下来而不是仅仅因为简单主题没有emit方法而发出。 next的功能完全相同(但EventEmitter上有下一个方法)

相关问题