Angular 角度可注入Toastr服务未定义
我创建了一个定制的Toastr服务(如果您愿意的话,更像是一个包装类)。我将它注入到我的数据服务(api调用)中,但每次调用它时,我都会得到一个错误,即它未定义。如果我在组件中使用此服务,那么它可以正常工作 我想这可能与我在Put通话中如何使用它有关 如何导出我的ToastarrapperClassAngular 角度可注入Toastr服务未定义,angular,angular8,toastr,Angular,Angular8,Toastr,我创建了一个定制的Toastr服务(如果您愿意的话,更像是一个包装类)。我将它注入到我的数据服务(api调用)中,但每次调用它时,我都会得到一个错误,即它未定义。如果我在组件中使用此服务,那么它可以正常工作 我想这可能与我在Put通话中如何使用它有关 如何导出我的ToastarrapperClass @Injectable() export class ToastrAlertService { 我在这里注入它,它引用了我正确的服务 @Injectable() export class User
@Injectable()
export class ToastrAlertService {
我在这里注入它,它引用了我正确的服务
@Injectable()
export class UserService {
constructor(
private http: HttpClient,
private apiEndpointService: ApiEndpointsService,
private adapter: UserAdapter,
private toastrAlertService: ToastrAlertService,
) { }
这里我称我的句柄错误(我想可能是因为我在这里处理“catchError”的方式)
public put(model: User): Observable<User> {
const headers = new HttpHeaders()
.set('Content-Type', 'application/json');
const putModel = {
Model: model,
};
return this.http.put(this.apiEndpointService.apiUrl(this.apiType + '/'), JSON.stringify(putModel), { headers }).pipe(
map((data: any) => this.adapter.adapt(data)), catchError(this.handleError),
);
}
您在哪里提供ToastrService?
从Angular 6.0开始创建单例服务的首选方法是在服务的
@Injectable()
装饰器上将providedIn
设置为root
。这告诉Angular在应用程序根目录中提供服务。()
以下是一些如何提供服务的示例:
应用程序模块:
@Injectable({
providedIn: 'root'
})
export class ToastrAlertService {
@Injectable({
providedIn: LazyLoadedModuleName
})
export class ToastrAlertService {
或
使用延迟加载的模块:
@Injectable({
providedIn: 'root'
})
export class ToastrAlertService {
@Injectable({
providedIn: LazyLoadedModuleName
})
export class ToastrAlertService {
按如下方式处理catchError为我解决了这个问题。(我确实将句柄错误逻辑移动到了一个类中,以使代码更干净)
这两个服务都存在于我的核心模块(ToastrAlertService和UserService)中。核心模块之外的其他组件可以很好地调用它。