问题
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