首先,确保您已经在 package.json 中安装了 auth0-js 和 auth0-angular。然后,在您的 app.module.ts 文件中,导入 AuthModule 和 HttpModule:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AuthModule } from 'auth0-angular';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule.withServerTransition({ appId: 'my-app' }),
AuthModule.forRoot({
domain: '',
clientId: ''
}),
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
注意:在 angular.json 文件中,需要把 "@auth0/angular-jwt" 添加到server 的allowedCommonJsDependencies选项中。如下所示:
"server": {
"builder": "@angular-devkit/build-angular:server",
"options": {
...
"allowedCommonJsDependencies": [
"@auth0/angular-jwt"
]
...
},
}
在组件中导入 AuthService,并在构造函数中注入它:
import { Component } from '@angular/core';
import { AuthService } from '@auth0/auth0-angular';
@Component({
selector: 'app-root',
template: `
Is authenticated: {{auth.isAuthenticated}}
`
})
export class AppComponent {
constructor(public auth: AuthService) {}
}
最后,在您的 server.ts 文件中,导入您的 app.module.ts(不要导入 AppModuleBrowser,因为我们要使用服务端渲染):
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { enableProdMode } from '@angular/core';
import * as express from 'express';
import { join } from 'path';
import { readFileSync } from 'fs';
import { AppServerModule } from './src/main.server';
import { APP_BASE_HREF } from '@angular/common';
import { ngExpressEngine } from '@nguniversal/express-engine';
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';
enableProdMode();
const app = express();
const port = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist');
const TEMPLATE = readFileSync(join(DIST_FOLDER, 'browser