【问题标题】:Need to access service in function需要在函数中访问服务
【发布时间】:2017-03-04 13:54:44
【问题描述】:

我有一个服务 (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 { }

【问题讨论】:

    标签: angular restangular angular2-services


    【解决方案1】:

    创建一个静态方法getToken() 然后您可以像在代码中一样访问它。

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

    【讨论】:

    • 问题是服务使用了一个promise从localforage获取token。所以请求是在设置令牌之前发送的:(
    【解决方案2】:

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

    【讨论】:

    • 问题是服务使用了一个promise从localforage获取token。所以请求是在设置令牌之前发送的:(
    • 为什么之前没有拿到token?
    • 有很多选项可以做到这一点,例如 APP_INITIALIZER、canActivate、resolver
    • 当应用程序启动时,我运行 AuthService localforage.getItem('auth').then((auth) => { 在此处提取令牌 });" 但是如果服务器的响应很慢,那么组件将在 promise 解决之前执行请求。
    猜你喜欢
    • 2012-09-25
    • 2011-02-11
    • 1970-01-01
    • 2011-09-09
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    相关资源
    最近更新 更多