【问题标题】:Protobuf with Angular 2.0 and asp.net core(webpack) and Typescript带有 Angular 2.0 和 asp.net core(webpack) 和 Typescript 的 Protobuf
【发布时间】:2020-04-08 22:20:35
【问题描述】:

protobuf.js 版本:“protobufjs”:“6.8.8”,

我是 protobufjs 的新手,并计划在 Angular 2 项目中实现 protobufjs。 我已经使用 Angular 2 项目(VS2015)中的“npm install protobufjs --save”安装了 protobufjs。

我有下面的服务,它将 http 请求发送到带有 Content-Type: application/x-protobuf 的 Restful 服务并以 protobuf 格式获取响应

getpersondetails(): Observable {
var headers = new Headers();
headers.append('Content-Type', 'application/x-protobuf');
return this.http.get('/system/data/getpersondetails', { headers });
}

获取如下示例响应, ↵*����Alex"(�0�↵&����Du���2355"

如何解码对下面模型对象的响应

//PerosnDetails.ts
export class PersonDetails
{
firstname:string;
lastname:string;
salary: number;
}

有人可以通过提供一些示例来帮助我,其中包含在 Angular 2 和 typescript 中获取请求的描述性步骤。

非常感谢任何帮助。

【问题讨论】:

    标签: angular typescript protobuf.js


    【解决方案1】:

    您想要原始(二进制)响应,因此您必须设置选项responseType: "arraybuffer"

    http.get('/system/data/getpersondetails', { 
      headers,
      responseType: "arraybuffer"
    });
    

    然后你可以从数组缓冲区中反序列化你的消息:

    let details = PersonDetails.deserializeBinary(yourArrayBuffer);
    

    但我建议使用 gRPC-web 或 Twirp,原因有两个:

    1. 您可以在 .proto 中使用 service 声明,并且可以为您生成客户端
    2. 您有一些 URL 映射和错误处理标准

    同样重要的是:google-protobuf 有很多很好的替代品。例如 ts-proto。 或者protobuf-ts(这是一个不要脸的插件,我是作者)。它有support for Angular

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-10
      • 1970-01-01
      • 1970-01-01
      • 2018-03-06
      • 1970-01-01
      • 2016-12-17
      • 2017-02-19
      • 1970-01-01
      相关资源
      最近更新 更多