簡體   English   中英

帶有 Angular 2.0 和 asp.net core(webpack) 和 Typescript 的 Protobuf

[英]Protobuf with Angular 2.0 and asp.net core(webpack) and Typescript

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 和打字稿中的 Get 請求的描述性步驟來幫助我。

任何幫助都非常感謝。

您需要原始(二進制)響應,因此您必須設置選項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 (這是一個不要臉的插件,我是作者)。 支持 Angular

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM