我有一个为所有功能返回Promise<???>
的服务(顺便说一句,这是一个好习惯吗?),例如
@Injectable()
export abstract class MyService {
abstract getCategories(): Promise<Category[]>;
}
我有两个impl,一个用于隔离测试,另一个用于部署时的远程。
@Injectable({
providedIn: 'root'
})
export class MyServiceLocalImpl implements MyService {
getCategories(): Promise<Category[]> {
return Promise.resolve(this.data.categories);
}
}
现在,当我将服务注入组件时,由于出现运行时错误,我无法保留Promise
值:
import {MyService} from "../services";
@Component({
selector: 'some-component',
templateUrl: './some-component.component.html',
styleUrls: ['./some-component.component.scss']
})
export class SomeComponent implements OnInit {
private service: MyService;
private categories: Category[];
constructor(service: MyService) {
this.service = service;
}
ngOnInit() {
this.service.getCategories().then( categories => {
this.categories = categories;
});
}
}
运行时错误:
ERROR TypeError: this.service.getCategories is not a function
更新,这是我的app.module.ts
@NgModule({
declarations: [
AppComponent,
SomeComponent
],
imports: [
BrowserModule,
HttpClientModule,
HttpClientXsrfModule.withOptions({
cookieName: 'Csrf-Token',
headerName: 'Csrf-Token',
}),
BootstrapModule,
FormsModule,
BrowserAnimationsModule
],
providers: [
AppService,
{
multi: true,
provide: HTTP_INTERCEPTORS,
useClass: AppHttpInterceptorService
},
{
multi: true,
provide: MyService,
useClass: MyServiceLocalImpl
}
],
bootstrap: [AppComponent]
})
export class AppModule {
}
答案 0 :(得分:1)
multi: true
意味着与令牌关联的“服务”实际上是一组服务实现。
以HTTP_INTERCEPTORS令牌为例,该令牌用于引用所有 HTTP拦截器。 http服务从注入器获取所有拦截器作为数组,然后一个接一个地调用它们。