我有一个身份验证服务,该服务会在发生错误时调用错误服务:
@Injectable({
providedIn: 'root'
})
export class AuthService {
private loginUrl:string = '/api/auth/login';
constructor(private httpClient:HttpClient, private errorService:ErrorService) { }
public login(credentials) {
let body = JSON.stringify(credentials);
return this.httpClient.post(this.loginUrl, body, httpOptions)
.pipe(
catchError(this.errorService.handleError)
)
}
}
ErrorService调用MessageService,它将错误消息添加到消息视图中显示的消息数组中。
@Injectable({
providedIn: 'root'
})
export class ErrorService {
constructor(private messageService:MessageService) { }
public handleError(error: Response | any) {
this.messageService.add('ERROR MESSAGE');
return of([])
}
}
如上所示,MessageService被注入到ErrorService的构造函数中。但是,当ErrorService的handleError函数在上面显示的代码行中调用messageService.add()函数时,MessageService被声明为未定义。
this.messageService.add('ERROR MESSAGE');
它会产生以下错误:
core.js:1624 ERROR TypeError: Cannot read property 'add' of undefined
at AuthService.push../src/app/shared/error/error.service.ts.ErrorService.handleError (error.service.ts:25)
at CatchSubscriber.push../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error (catchError.js:33)
MessageService:
@Injectable({
providedIn: 'root'
})
export class MessageService {
public messages: string[] = [];
constructor() { }
add(message:string) {
this.messages.push(message);
setTimeout(() => {
this.clear();
}, 20000)
}
clear() {
this.messages = [];
}
}