【问题标题】:how to subscribe the Id of the created object after POST operationPOST操作后如何订阅创建对象的Id
【发布时间】:2019-04-05 09:11:09
【问题描述】:

我有一个组件,我通过像这样调用api 添加一个名为customer 的新对象:

  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。

【问题讨论】:

  • 这个“另一个组件”与组件有什么关系?有没有父子关系?
  • 没有父子关系
  • 我想在same component 或其他component 中获取added object ID

标签: javascript angular typescript angular6


【解决方案1】:

这完全取决于您的应用程序的设计和组件之间的关系。您可以使用主题将数据多播给多个订阅者。

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

【讨论】:

  • 其实我也写了单独的services用于组件之间的通信,但是在这个scenario中我应该只从api获取response
  • 只有 api 是什么意思?你的意思是 observable 应该在组件之间共享?
  • 表示addCustomer 文件中存在的addCustomer 方法,我在这里调用api。
  • 是的,答案就是这样。响应到来后,使用主题发出值。所以谁订阅了它就会得到价值。
猜你喜欢
  • 2017-08-28
  • 2021-11-01
  • 2014-04-08
  • 2013-08-22
  • 1970-01-01
  • 2020-04-27
  • 2019-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多