导入未被组件文件

时间:2016-10-12 14:35:40

标签: angular typescript

我正在开发一个简单的Angular 2项目,我的所有导入工作都在我的app.module.ts文件中,如下所示

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { StockListComponent } from './stock-list/stock-list.component';

import { routing } from "./app-routing.module";
import { StockItemComponent } from './stock-item/stock-item.component';
import { ProfileComponent } from './profile/profile.component';
import { DeviceConfigurationComponent } from './device-configuration/device-configuration.component';
import { StockStatusComponent } from './stock-status/stock-status.component';


import {Calendar, Dialog, Button, InputSwitch, Dropdown, Growl, DataTable, SelectButtonModule} from 'primeng/primeng';
import {JwtHelper, AuthHttp, tokenNotExpired} from "angular2-jwt";

import {AuthService} from './auth.service';
import {DataService} from './data.service';

@NgModule({
 declarations: [
  AppComponent,
  StockListComponent,
  StockItemComponent,
  ProfileComponent,
  DeviceConfigurationComponent,
  StockStatusComponent
],
imports: [
  BrowserModule,
  FormsModule,
  HttpModule,
  routing,
  DataTable,
  Calendar,
  Dialog,
  Button,
  InputSwitch,
  Dropdown,
  Growl,
  JwtHelper,
  AuthHttp,
  SelectButtonModule
],
providers: [
  AuthService,
  DataService
],
bootstrap: [AppComponent]
})
export class AppModule { }

但是我在我的控制台中遇到与我的一个component.ts文件有关的错误,即使它们已经在app.module.ts中导入,也找不到这些名称

错误

错误在[默认] /Users/~/src/app/stock-list/stock-list.component.ts:42:26 找不到名称'AuthService'。

1 个答案:

答案 0 :(得分:3)

如果您想在AuthService上调用方法,则必须在组件中再次导入它并注入它,以便可以引用它。

例如:

import { AuthService } from '../auth.service'; // edit path according to your structure

接下来,您应该在组件中注入服务,如下所示:

constructor(private auth: AuthService) { }

现在您可以在组件的方法中引用AuthService,例如:

myComponentMethod() {
   this.auth.logout();
}