如何返回Http响应?

Roo*_*omy 1 javascript rxjs typescript angular

我想知道是否可以做以下事情:

我需要GET直接从http 请求返回响应,而不是返回Observable<Response>实例.

这个例子可能会澄清整个事情:

@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]
  }
}
Run Code Online (Sandbox Code Playgroud)

总结:根据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()
    })
  }
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 5

这是不可能的,因为HTTP请求是异步的,并且get()方法在甚至进行对服务器的调用之前返回.相反,当来自服务器的响应到达时,调用传递给的回调subscribe(...).

没有办法从异步返回到同步执行.

您只能返回调用者的observable来订阅它,并在响应到达时执行某些操作.