2017-03-04 65 views
4

我有一個服務(AuthService),我需要在我的restangularInit函數(在我的app.module.ts中)訪問,但我不知道如何,我無法訪問它。需要訪問服務的功能

我試圖將它移動到類AppModule,但到那時就要遲到了。

調用服務功能,例如, getToken按預期工作。

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

創建一個靜態方法getToken()那麼你可以像你在你的代碼做訪問它。

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

的問題是,該服務使用的承諾,從localforage取令牌。所以這些請求在令牌設置之前發送:( – Mackelito

1

按照documentation,你可以不喜歡它::

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

問題在於服務使用承諾從localforage獲取令牌,所以請求在令牌設置之前發送: – Mackelito

+0

爲什麼您在獲取令牌之前沒有獲取令牌? – yurzui

+0

有很多選項可以做到像APP_INITIALIZER,canActivate,resolver – yurzui