我无法将数据发送到后端,我不知道为什么,控制台中的问题恰好出现在登录和注册组件中,出现了同样的问题。也许ngsubmit的格式设置有误,但我不知道如何通过它需要代表的模式来发布(ngSubmit)=“ onSubmit(f)”。 这是控制台和正在使用的组件中的错误。
TypeError: Cannot set property 'router' of undefined
at AuthInceptor (auth.interceptor.ts:11)
at eval (module.ngfactory.js? [sm]:1)
at _callFactory (core.js:21283)
at _createProviderInstance (core.js:21237)
at resolveNgModuleDep (core.js:21198)
at NgModuleRef_.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef_.get
auth.service.ts
constructor(private router: Router, private httpClient: HttpClient) {}
LogIn(email: string, password: string) {
const reqHeader = new HttpHeaders({'Content-Type': 'application/json', 'No-Auth': 'True'});
return this.httpClient.post<any>(this.apiAddress + 'account/login', {
Email: email,
Password: password
}, {headers: reqHeader})
.catch((e: any) => Observable.throw(this.errorHandler(e)));
}
Register(name: string, email: string, password: string, role: string) {
const reqHeader = new HttpHeaders({'Content-Type': 'application/json', 'No-Auth': 'True'});
return this.httpClient.post<any>(this.apiAddress + 'account/register', {
Name: name,
Email: email,
Password: password,
Role: role
}, {headers: reqHeader})
.catch((e: any) => Observable.throw(this.errorHandler(e)));
}
errorHandler(error: any): void {
console.log(error);
}
auth.inceptor.ts
constructor(private router: Router) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.headers.get('No-Auth') === 'True') {
return next.handle(req.clone());
}
if (localStorage.getItem('userToken') != null) {
const clonedreq = req.clone({
headers: req.headers.set('Authorization', 'Bearer ' + localStorage.getItem('userToken'))
});
return next.handle(clonedreq)
.do(
succ => { },
err => {
if (err.status === 401) {
this.router.navigate(['/login']);
}
}
);
} else {
this.router.navigate(['/login']);
}
}
登录表格
<form class="example-form" (ngSubmit)="onSubmit(email.value, password.value)" #f="ngForm">
<mat-card-content>
<table class="example-full-width" cellspacing="0">
<tr>
<td>
<mat-form-field class="example-full-width">
<input matInput placeholder="Email" #email ngModel name="email" required>
</mat-form-field>
</td>
</tr>
<tr>
<td><mat-form-field class="example-full-width">
<input matInput placeholder="Password" #password ngModel type="password" name="password" required>
</mat-form-field></td>
</tr></table>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button type="submit" color="primary">Login</button>
<div *ngIf="isLoginError" class="red-text center error-message">Error Incorrect email or password</div>
</mat-card-actions>
</form>
提交功能
onSubmit(email, password): void {
this.authService.LogIn(email, password)
.subscribe((data: any) => {
localStorage.setItem('userToken', data.token);
localStorage.setItem('role', data.role);
this.router.navigate(['../Home']);
console.log(data);
},
(err: HttpErrorResponse) => {
this.isLoginError = true;
});
}