要解决Angular 9通用服务端渲染GRPC错误,您可以按照以下步骤进行操作:
"dependencies": {
"@angular/platform-server": "^9.0.0",
"grpc": "^1.24.2",
"grpc-web": "^1.0.6"
}
GrpcService
的服务:import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { grpc } from 'grpc-web-client';
import { YourGRPCService } from './yourgrpcservice_pb_service';
import { YourRequest, YourResponse } from './yourgrpcservice_pb';
@Injectable()
export class GrpcService {
private grpcService: YourGRPCService;
constructor() {
this.grpcService = new YourGRPCService('http://localhost:8080', null, null);
}
public callGRPC(request: YourRequest): Observable {
return new Observable(observer => {
grpc.unary(YourGRPCService.YourMethod, {
request: request,
host: 'http://localhost:8080',
onEnd: res => {
const { status, statusMessage, headers, message, trailers } = res;
if (status === grpc.Code.OK && message) {
observer.next(message);
observer.complete();
} else {
observer.error({ status, statusMessage, headers, message, trailers });
}
}
});
});
}
}
server.ts
的文件:import { enableProdMode } from '@angular/core';
import { createServerRenderer, RenderResult } from 'aspnet-prerendering';
import { AppServerModule } from './src/app/app.server.module';
import { GrpcService } from './src/app/grpc.service';
import { YourRequest } from './src/app/yourgrpcservice_pb';
export default createServerRenderer(params => {
const grpcService = new GrpcService();
const request: YourRequest = new YourRequest();
return new Promise((resolve, reject) => {
grpcService.callGRPC(request).subscribe(
response => {
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = response;
enableProdMode();
const moduleRef = AppServerModuleNgFactory.create(global);
const { AppServerModule, AppModule } = moduleRef.instance;
const providers = [
{ provide: 'REQUEST', useFactory: () => params, deps: [] },
{ provide: 'RESPONSE', useFactory: () => response, deps: [] },
{ provide: GrpcService, useFactory: () => grpcService, deps: [] },
...AppServerModule.providers,
...AppModule.providers
];
moduleRef.injector.get(YourGRPCService).preFetchData().then(() => {
resolve({
html: response.html,
globals: {
appModuleFactory: moduleRef,
AppServerModule,
LAZY_MODULE_MAP,
providers
}
});
});
},
error => {
reject(error);
}
);
});
});
请根据您的实际需求修改上述代码,确保在创建和调用GRPC服务时使用正确的类和方法。
这些步骤应该能够帮助您解决Angular 9通用服务端渲染GRPC错误。请不要忘记将代码中的YourGRPCService
和YourRequest
替换为您实际使用的GRPC服务和请求对象。