How do I pass data to Angular routed components?

前端 未结 16 1309
挽巷
挽巷 2020-11-22 08:03

In one of my Angular 2 routes\'s templates (FirstComponent) I have a button

first.component.html

16条回答
  •  一向
    一向 (楼主)
    2020-11-22 08:43

    You can use BehaviorSubject for sharing data between routed components. A BehaviorSubject holds one value. When it is subscribed it emits the value immediately. A Subject doesn't hold a value.

    In the service.

    @Injectable({
      providedIn: 'root'
    })
    export class CustomerReportService extends BaseService {
      reportFilter = new BehaviorSubject(null);
      constructor(private httpClient: HttpClient) { super(); }
    
      getCustomerBalanceDetails(reportFilter: ReportFilterVM): Observable> {
        return this.httpClient.post>(this.apiBaseURL + 'CustomerReport/CustomerBalanceDetail', reportFilter);
      }
    }
    

    In the component you can subscribe to this BehaviorSubject.

    this.reportService.reportFilter.subscribe(f => {
          if (f) {
            this.reportFilter = f;
          }
        });
    

    Note: Subject won't work here, Need to use Behavior Subject only.

提交回复
热议问题