Need to access service in function

坚强是说给别人听的谎言 提交于 2021-02-20 18:43:35

问题


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.

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

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 { }

回答1:


Create a static method getToken() then you can access it like you did in your code.

let token = AuthService.getToken(); //This is what I want to do



回答2:


According to the documentation you can do it like::

RestangularModule.forRoot([AuthService], restangularInit)

and then

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},
  );
}


来源:https://stackoverflow.com/questions/42596824/need-to-access-service-in-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!