如何在POST操作后订阅已创建对象的Id

问题描述 投票:1回答:1

我有一个组件,我通过调用customer添加一个名为api的新对象,如下所示:

  public onAdd(): void {
    this.myCustomer = this.customerForm.value; 
    this.myService.addCustomer(this.myCustome).subscribe(
      () => {  // If POST is success
        this.callSuccessMethod(); 
      },
      (error) => { // If POST is failed
       this.callFailureMethod();
      },
    );

 }

服务文件:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import {ICustomer } from 'src/app/models/app.models';

@Injectable({
  providedIn: 'root',
})

export class MyService {
 private  baseUrl : string = '....URL....';
 constructor(private http: HttpClient) {}


public addCustomer(customer: ICustomer): Observable<object> {
  const apiUrl: string = `${this.baseUrl}/customers`;

  return this.http.post(apiUrl, customer);
}

}

如组件代码所示,我已经订阅了api调用,如下所示:

this.myService.addCustomer(this.myCustome).subscribe(
          () => {  // If POST is success
            .....
          },
          (error) => { // If POST is failed
           ...
          },
        );

但是,我想在另一个组件中订阅结果,我试过这样:

public  getAddedCustomer() { 
    this.myService.addCustomer().subscribe(
      (data:ICustomer) => { 
        this.addedCustomer.id = data.id; <======
      }
    );
  }

我得到这个lint错误:Expected 1 arguments, but got 0因为我没有通过任何parameter

在其他组件中订阅api调用的正确方法是什么? POST操作后。

因为我想为其他功能添加对象ID。

javascript angular typescript angular6
1个回答
0
投票

那么它完全取决于应用程序的设计和组件之间的关系。您可以使用Subjects将数据多播到多个订阅者。

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { ICustomer } from 'src/app/models/app.models';

@Injectable({
  providedIn: 'root',
})

export class MyService {
 private  baseUrl : string = '....URL....';
 private latestAddedCustomer = new Subject();
 public latestAddedCustomer$ = this.latestAddedCustomer.asObservable()
 constructor(private http: HttpClient) {}


public addCustomer(customer: ICustomer): Observable<object> {
  const apiUrl: string = `${this.baseUrl}/customers`;

  return this.http.post(apiUrl, customer).pipe(map((data) => this.latestAddedCustomer.next(data)));
}

}

并按如下方式订阅该主题

this.latestAddedCustomer$.subscribe()

应该为您提供最新的客户详细信息。即使我不这样写它的方式。我基本上会编写一个单独的服务来共享组件之间的数据,或者如果它在整个应用程序中使用,则会编写一个缓存服务。但这里的想法是使用主题的概念。你可以阅读更多关于它Here

© www.soinside.com 2019 - 2024. All rights reserved.