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

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

问题描述

我需要在我的 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天全站免登陆