.net core & Angular => gRPC
更多可以參考:
只是測試連接成功了孽拷,數(shù)據(jù)處理什么的都沒有做
- 直接使用vs 2019 創(chuàng)建 grpc 項目
- nuget 安裝Grpc.AspNetCore.Web(測試版本:2.27.0-pre1) (測試時還不是正式版)
- 修改代碼 Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("MyPolicy",
builder =>
{
builder.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddGrpc();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors("MyPolicy");
app.UseGrpcWeb();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<GreeterService>().EnableGrpcWeb(); // EnableGrpcWeb() 需要這個方法 依賴于庫 Grpc.AspNetCore.Web (測試版本:2.27.0-pre1)
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
});
});
}
- 創(chuàng)建angular項目
- 需要依賴庫
- ts-protoc-gen
- google-protobuf
- @types/google-protobuf
- @improbable-eng/grpc-web
yarn add ts-protoc-gen google-protobuf @types/google-protobuf @improbable-eng/grpc-web
- 編譯proto文件
- protoc 命令 https://github.com/protocolbuffers/protobuf/releases
- 下載解壓把bin目錄添加到系統(tǒng)環(huán)境變量
- 編譯的js和ts文件放到同一個目錄下
- protoc -I=I:/Protos greet.proto --plugin=./node_modules/.bin/protoc-gen-ts.cmd --js_out=import_style=commonjs,binary:src/app/proto --ts_out=service=grpc-web:src/app/proto
protoc -I=<proto文件所在目錄(使用絕對路徑)> <編譯的文件.proto> --plugin=./node_modules/.bin/protoc-gen-ts.cmd --js_out=import_style=commonjs,binary:<編譯成的js文件放置的目錄> --ts_out=service=grpc-web:<編譯成的ts文件放置的目錄>
- app.component.ts
import { Component, OnInit } from '@angular/core';
import { grpc } from '@improbable-eng/grpc-web';
import { Greeter } from './proto/greet_pb_service';
import { HelloRequest } from './proto/greet_pb';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent implements OnInit {
title = 'ng-web';
ngOnInit() {
const getBookRequest = new HelloRequest();
grpc.unary(Greeter.SayHello, {
request: getBookRequest,
host: 'https://localhost:5001',
onEnd: res => {
console.log(res);
}
});
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者