在我向项目中添加service(dish.service.ts)之前,我刚刚开始学习角度一切都很好。
这是错误 ./src/app/services/dish.service.ts 模块解析失败:意外的令牌(15:13) 您可能需要适当的加载程序来处理此文件类型。
dish.service.ts
import { Injectable } from '@angular/core';
import { Dish } from '../shared/dish';
import { Dishes } from '../shared/dishes';
@Injectable({
providedIn: 'root'
})
export class DishService {
constructor() {
getDishes():Dish[]{
return DISHES;
}
}
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platformbrowser/animations';
import { MatToolbarModule } from '@angular/material/toolbar';
import { FlexLayoutModule } from '@angular/flex-layout';
import { MatListModule } from '@angular/material/list';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { AppComponent } from './app.component';
import 'hammerjs';
import { MenuComponent } from './menu/menu.component';
import { DishDetailsComponent } from './dish-details/dish-details.component';
import { DishService } from './services/dish.service';
@NgModule({
declarations: [
AppComponent,
MenuComponent,
DishDetailsComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatToolbarModule,
MatListModule,
MatGridListModule,
MatCardModule,
MatButtonModule,
FlexLayoutModule
],
providers: [ DishService ],
bootstrap: [AppComponent]
})
export class AppModule { }
答案 0 :(得分:0)
不过,您可以根据需要使用多种方式使用服务 您要如何处理
1)将服务放入app.module.ts
通过在提供程序数组中添加服务,这意味着在您的应用程序中您想要维护服务的单个实例,并且想要将一个服务注入另一个服务
例如: //导入服务 提供者:[yourseriviceName] 这将创建一个实例也没有添加 @Injectable({ providerIn:'root' }),因为它不需要。
2)如果您只想在组件中导入并且想要该服务的多个实例
service.ts
export class dummyService {
constructor(parameters) {
}
yourMethod(){
return //Something
}
}
component.ts
import your service as well
@Component({
selector: 'dummy',
styleUrls: ['dummy.component.sass'],
templateUrl: 'dummy.component.html',
providers:[dummyService]
})
export class yourComponentName {
constructor(private dummyservice:dummyService) {
}
//Acces your service via
this.dummyservice.yourMethod()
}
3)当您想将一项服务注入另一项服务时:
//import injectable from angular core
//import your service which you want to inject
//Note ensure you import injectable first and then your service
@injectable()
export class dummyService {
constructor(parameters) {
}
yourMethod(){
return //Something
}
}
解决您的问题是方法在构造函数中,以便在打字稿中创建类时为您提供更好的概述,首先执行构造函数,然后再执行其他角度生命周期挂钩 因此,请参考我的第二点,并将您的方法保留在构造函数之外,并按照我在component.ts中显示的方法进行访问