如何发送响应到另一个组件

时间:2018-12-15 11:04:00

标签: angular

任何人都可以告诉我,我正在基于该ID向后端发送“ ID”,我正在获取用户详细信息。我将此用户详细信息存储在x对象中。我正在使用BehaviorSubject将x对象发送到另一个组件,但是数据没有发送到另一个组件。有人请告诉我问题是什么。我需要放什么。

reviewcomponent.html

<i class="fas fa-edit" routerLink='/dashboard-info/review-edit'

reviewcomponent.ts

editUserDetails:any=[];
    editIssue(id, detail) {
      alert(detail);
      let data = {
        _id: detail,
      };
      this.accountService.editreviewDetail(data).subscribe(
        response => {
          this.editUserDetails = response;
          let data1=this.editUserDetails
              this.accountService.sendedit(data1)
        },
        err => {
          console.error('User Not found');
        }) 
    }

帐户服务

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DataService } from './data.service';
import {BehaviorSubject} from 'rxjs';
import { Observable } from 'rxjs';

@Injectable()
export class AccountService {
    private user=new BehaviorSubject<string>('');
    cast=this.user.asObservable();
    public apiPath: string;//Api URL where we need to send our data & perform related operations
    constructor(ds: DataService, private http: HttpClient) {
        this.apiPath = ds.apiPath;
    }

    sendedit(newUser){
        return this.user.next(newUser)
    }

}

reviewedit.component.ts

ngOnInit() {
    this.accountService.cast.subscribe(user=>this.editUserDetails=user);
    console.log(this.editUserDetails);
}
当我console.log(this.editUserDetails)在reviewit.component.ts中时,什么都没有显示。 这里editUserDetails:any = [];

1 个答案:

答案 0 :(得分:-1)

  

BehaviorSubject是Subject的一种变体,它的概念是“当前值”。它存储了发给其使用者的最新值,并且每当有新的Observer进行订阅时,它将立即从BehaviorSubject接收“当前值”。

您可以并且应该直接订阅BehaviorSubject。这样,您将始终获得当前值。无需将其强制转换为Observable。

因此在您的 rewiewedit.component.ts 中:

ngOnInit() {
    this.accountService.user
        .subscribe(user => {
            this.editUserDetails=user;
            console.log(this.editUserDetails);
    });
}

PS:别忘了公开您的BehaviorSubject。