如何将可观察的响应转换为本地对象 [英] How to cast observable response to local object

查看:29
本文介绍了如何将可观察的响应转换为本地对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在当前的 Angular 6 应用程序中,订阅了 observable(来自 RESTful 服务的响应)

In current Angular 6 application there is a subscribe to observable (response from RESTful service)

  this.activatedRoute.data.subscribe(({bag}) => {
    console.log(bag);
    this.bag= bag;
  });

订阅正在等待解析器的响应

the subscription is waiting response from resolver

@Injectable({
  providedIn: 'root'
})
export class BagResolver implements Resolve<Bag> {
  constructor(private service: BagService) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const id = route.params['id'] ? route.params['id'] : null;
    if (id) {
      const existingBag = this.service.find(id).pipe(map((bag: HttpResponse<Bag>) => bag.body));
      return existingBag;
    }

    return of(new Bag());
  }
}

运行调试模式,我发现包是一个遵循结构的对象

Ran a debug mode I found bag is an object with follow structure

Object
{headers:,
 body{id:10, name:aName, ...},  <-- this is the actual bag object
 statusCode:"OK",
 statusCodeValue:"200"
 }

所以订阅中的 bag 并不是真正的 bag 对象,而是看起来像一个 http 响应,它将 bag 对象包裹在其主体中

So bag in the subscription is not really a bag object but looks like a http response which wrapped the bag object in its body

现在我真的想从上面的对象中提取 body 并转换为本地对象

Now I really want to extract the body from above object and cast to local object

那么如何安全地提取数据并从 subscribe(...) 返回的上面转换对象?

So then how to safely extract the data and cast the object from above return from subscribe(...)?

推荐答案

我怀疑这个对象是一个 来自 Spring 的 ResponseEntity不是来自 angular 的 HttpResponse. 告诉是statusCodeValue 这不是 Angular 的 HttpResponse 的属性.如果您正在序列化spring ResponseEntitys并将它们作为响应发送并观察响应body(间接或直接—这里都出现),您需要在前端创建一个类似的界面并使用它在您的服务中:

I suspect that this object is a ResponseEntity from Spring and not a HttpResponse from angular. The tell is statusCodeValue which is not a property of angular's HttpResponse. If you are serializing spring ResponseEntitys and sending them as the response AND observing the response body (indirectly or directly—which all appear true here), you need to create a similar interface in the front-end and use it in your service:

interface ResponseEntity<T> {
   headers: { [headerName: string]: string },
   body: T,
   statusCode: "OK" | "SERVER_ERROR" | "BAD_REQUEST", //etc
   statusCodeValue: "200" | "500" | "400" | "404" //etc
}

示例服务

import { ResponseEntity } from "./dir/dir/file";

class BagService {
    constructor(http: HttpClient) {}

    find(id: string): Observable<Bag> {
        return this.http.get<ResponseEntity<Bag>>(`/bag/${id}`).pipe(
            map(resp => resp.body)
        );
    }
}

我希望这会有所帮助!

这篇关于如何将可观察的响应转换为本地对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆