如何编写一个发出 http 请求并 return 请求结果的函数?

How to write a function that make http request and return the result of the request?

函数 getEventId() 是 returning this.eventId

如果this.eventId == null,

  1. 正在调用一个发出 http 请求的函数。

  2. this.eventId = resp(请求的响应)。

    ngOnInit() { // 下面的函数发出 http 请求。 this.getCustomerFileByCode().订阅(数据=>{ // 从服务器获取ID this.eventId = 数据[0]; }) }

    getEventId() { if (this.eventId) { //如果服务器请求 returned 已经响应 return 个(this.eventId) } 别的 { getCustomerFileByCode().subscrive(数据=>{ this.eventId = 数据[0] }) // 等待一些服务器响应和 return 值 return this.eventId; }) } }

    getCustomerFileByCode():可观察{ return this.http.post(this._url, JSON.stringify(参数), this.options) }

如何在函数 getEventId() 中 return 来自 http 请求的值?

我想你想做一些类似的事情

getEventId(elementId):Observable<any> {
    if (this.eventId) { //if the server request returned already 
        return of(this.eventId)
    } else {
        return this.getCustomerFileByCode(elementId).pipe(
         map(data=>data[0]),
         tap(res => { 
            this.eventId = res;
        })
    }

并且在 ngOnInit

    this.getEventId(this.elementId).subscribe(()=> { 
          ...make something more...
          ...don't worry about this.eventId because the "tap" ...
          ...on the observable yet store the value...
    })

看到 getEventId return 一个 observable,如果 "this.eventId" 是,只需 return 的,否则调用 API,转换响应 -使用 map- 并使用 tap- 存储值。当然,作为所有可观察对象,您需要订阅“启动”。好吧,你可以在订阅中等于 teh 值,不要使用“tap”。但一般来说,可观察对象必须在服务中声明并在组件中订阅,因此变量“属于”服务更符合逻辑。