简体   繁体   English

如何返回Http响应?

[英]How can I return the Http response?

I'm wondering if following thing is possible to do: 我想知道是否可以做以下事情:

I need to return the response from http GET request directly instead of returning Observable<Response> instance. 我需要直接从http GET请求返回响应,而不是返回Observable<Response>实例。

The example might clarify whole thing a bit: 该示例可能会澄清整个事情:

@Injectable()
export class ExampleService {
  constructor( @Inject(Http) protected http: Http) { }
  static model: { [uri: string]: any } = {}
  public get(uri: string): any {
    if (typeof ExampleService.model[uri] === 'undefined') {
      ExampleService.model[uri] = this.http.get(uri).map(response => response.json()) // additionally do some magic here, it is Observable<any> instance now
    }
    return ExampleService.model[uri]
  }
}

Summary: according to Günter Zöchbauer answer above solution is not possible, instead of that I need to use something like this: 简介:根据GünterZöchbauer的回答,上述解决方案是不可能的,相反,我需要使用以下方法:

  public get(uri: string): Observable<any> {
    return new Observable(observer => {
      if (!ExampleService.model[uri]) {
        let sub = this.http.get(uri).map(response => response.json()).subscribe(
          src => observer.next(ExampleService.model[uri] = src),
          err => console.error(err),
          () => observer.complete()
        )
        return () => sub.unsubscribe()
      }
      observer.next(ExampleService.model[uri])
      observer.complete()
    })
  }

This is not possible because the HTTP request is async and the get() method returns before the call to the server is even made. 这是不可能的,因为HTTP请求是异步的,并且get()方法在调用服务器之前就已返回。 Instead when the response from the server arrives the callback passed to subscribe(...) is called. 相反,当服务器的响应到达时,将调用传递给subscribe(...)的回调。

There is no way to go back from async to sync execution. 没有办法从异步返回到同步执行。

You can only return the observable for the caller to subscribe to it and do something when the response arrives. 您只能返回可观察对象,以便调用者订阅它并在响应到达时执行某些操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM