需要访问功能中的服务 [英] Need to access service in function

查看:89
本文介绍了需要访问功能中的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要通过我的 restangularInit 函数(在我的app.module.ts中)访问的服务(AuthService),但我不知道如何,我无法访问它.

I have a service (AuthService) that I need to access in my restangularInit function (in my app.module.ts) but I don't know how, I can't get access to it.

我试图将其移至AppModule类,但到现在为止已经很晚了.

I have tried to move it to the class AppModule but by then it´s to late.

调用服务功能,例如 getToken 可以正常工作.

Calling the service functions eg. getToken works as expected.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { MaterialModule } from '@angular/material';
import { FlexLayoutModule } from "@angular/flex-layout";
import { RestangularModule } from 'ng2-restangular';

// Components
import { AppComponent } from './app.component';
import { ProductComponent } from './components/product/product.component';

// Services
import { AuthService } from './services/auth.service';

export function restangularInit(RestangularProvider, AuthService) {
  console.log(AuthService); // this is undefined
  let token = AuthService.getToken(); //This is what I want to do
  RestangularProvider.setBaseUrl('api');
  RestangularProvider.setDefaultHeaders(
    {'Authorization': 'Bearer ' + token},
  );
}

@NgModule({
  declarations: [
    AppComponent,
    ProductComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    MaterialModule,
    FlexLayoutModule,
    RestangularModule.forRoot(restangularInit)
  ],
  providers: [
    AuthService
  ],
  entryComponents: [ProductComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }

推荐答案

根据

According to the documentation you can do it like::

RestangularModule.forRoot([AuthService], restangularInit)

然后

export function restangularInit(RestangularProvider, authService: AuthService) {
  console.log(authService); // this is AuthService instance
  let token = authService.getToken(); //This is what I want to do
  RestangularProvider.setBaseUrl('api');
  RestangularProvider.setDefaultHeaders(
    {'Authorization': 'Bearer ' + token},
  );
}

这篇关于需要访问功能中的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆