提供HTTP_INTERCEPTORS不适用于SSR

时间:2019-10-30 08:33:27

标签: angular angular-universal server-side-rendering

一旦添加HTTP_INTERCEPTORS提供语句,应用程序就会挂起,没有它,应用程序也可以正常运行(即使我是空的MyInterceptor类。)

MyINTERCEPTOR.ts

...
constructor(
    private  loaderService: LoaderService,
    private  authService: AuthService
  ) {
  }

  intercept<T>(
    req: HttpRequest<T>,
    next: HttpHandler
  ): Observable<HttpEvent<T>> {
    this.loaderService.requestBegin();
    this.authService.setHeaders(req, next).pipe(
      catchError((error) => {
        this.loaderService.requestEnded();
        return throwError(error);
      })
    );
    return next.handle(req);
  }
  ...

MyModule.ts ...

providers: [
     ...,
    { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }, // the app run without this line.
]
.

package.json

"@angular/core": "^7.2.7",
"@angular/platform-server": "^7.2.7",
"@angular/pwa": "^0.12.4",
"@angular/service-worker": "^7.2.7",
"@nguniversal/express-engine": "^7.1.1",
"@nguniversal/module-map-ngfactory-loader": "^7.1.1",

server.ts

...
app.engine('html', (_, options, callback) => {
  const engine = ngExpressEngine({
    bootstrap: AppServerModuleNgFactory,
    providers: [
      provideModuleMap(LAZY_MODULE_MAP),
      {provide: 'host', useFactory: () => options.req.get('host'), deps: []}
    ]
  });
  engine(_, options, callback);
});

app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));

// Serve static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, 'browser'), {
  maxAge: '1y'
}));

// All regular routes use the Universal engine
// app.get('*', (req, res) => {
//   res.render('index', {req});
// });

app.get('*', (req, res) => { res.sendFile( join(DIST_FOLDER, 'browser' , 'index.html'), {req}); });

tsconfig.server.json

{
"extends": "./tsconfig.app.json",
"compilerOptions": {
 "outDir": "../out-tsc/app-server",
 "baseUrl": "."
},
"angularCompilerOptions": {
 "entryModule": "app/app.server.module#AppServerModule"
}
}


angular.json

....
"server": {
       "builder": "@angular-devkit/build-angular:server",
       "options": {
         "outputPath": "dist/server",
         "main": "src/main.server.ts",
         "tsConfig": "src/tsconfig.server.json"
       },
       "configurations": {
         "production": {
           "fileReplacements": [
             {
               "replace": "src/environments/environment.ts",
               "with": "src/environments/environment.prod.ts"
             }
           ]
         }
       }
     }
   ....

package.json

"scripts": {
...
"compile:server": "webpack --config webpack.server.config.js --progress --colors",
 "serve:ssr": "node dist/server",
 "build:ssr": "npm run build:client-and-server-bundles && npm run compile:server",
 "build:client-and-server-bundles": "ng build --prod && ng run my-project:server:production",
 "ssr-only": "ng run my-project:server:production && npm run compile:server && node dist/server"
....
}

我的项目出了什么问题?

0 个答案:

没有答案