The need to access the service in the function

I have a service (AuthService) that I need to access in my function restangularInit(in my .module.ts application), but I don’t know how, I can’t access it.

I tried to port it to the AppModule class, but by the end of this time it is late.

Calling service functions, for example. getTokenworks 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 { }
+4
source share
2 answers

Create a static method getToken(), after which you can access it, as in the code.

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

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

Source: https://habr.com/ru/post/1671446/


All Articles