Angular Сервис вызывается дважды в лениво загруженных модулях - PullRequest
0 голосов
/ 30 апреля 2020

Я создаю Angular приложение, в котором реализована отложенная загрузка. Он работает нормально, но когда я делаю HTTP-запрос к серверу, действие происходит дважды.

В моей текущей структуре я создал общий модуль для хранения всех общих модулей и компонентов. Я использую сервис ajax для выполнения всех вызовов API для серверной части, AuthTokenService - для хранения и обработки токена аутентификации -

Функциональный модуль -

import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';

//Importing HTTP Intercepter and services
import { HTTPInterceptorProvider } from '@/core/_HTTP-interceptor';
import { AjaxService, AuthTokenService } from '@/core/_services';

//Importing pipes
import { SummaryPipe } from '@/core/_pipes';

//Externel Plugins Modules
import { NgSelectModule } from '@ng-select/ng-select';

import { AnimatedNumbersComponent } from '@/modules/shared';

@NgModule({
  declarations: [
    AnimatedNumbersComponent,
    //Pipes used are listed here
    SummaryPipe
  ],
  imports: [
    CommonModule,
    ReactiveFormsModule,
    FormsModule,
    RouterModule,
    NgSelectModule
  ],
  providers: [
  ],
  exports: [
    AnimatedNumbersComponent,

    ReactiveFormsModule,
    FormsModule,
    NgSelectModule
  ]
})
export class FeatureModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: FeatureModule,
      providers: [
        AjaxService,
        AuthTokenService,
        HTTPInterceptorProvider
      ]
    };
  }
}

Модуль приложения -

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule, routingComponents } from './app-routing.module';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
import { FeatureModule } from './modules/featured/feature.module'

import { DatePipe } from '@angular/common';
import { NgxSpinnerModule } from "ngx-spinner";
import { AppComponent } from '@/app.component';


@NgModule({
  declarations: [
    AppComponent,
    routingComponents
  ],
  imports: [
    HttpClientModule,
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    NgxSpinnerModule, // NGX Spinner
    FeatureModule.forRoot()
  ],
  providers: [
    DatePipe
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Модуль маршрутизации приложения -

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard, SecureOuterPagesGuard, SecureInnerPagesGuard } from "@/core/_guards";

// Home page of the application
import { IndexComponent } from '@/modules/index/index.component';
import { 
  LoginComponent, 
  RegisterComponent,
  ForgetPasswordComponent,
  ResetPasswordComponent 
} from '@/modules/auth';

import {
  PageNotFoundComponent,
  InternalServerErrorComponent
} from '@/modules/shared';


const routes: Routes = [
  {
    path: '',
    component: IndexComponent
  },
  {
    path: 'login',
    component: LoginComponent,
    canActivate: [SecureOuterPagesGuard]
  },
  {
    path: 'register',
    component: RegisterComponent,
    canActivate: [SecureOuterPagesGuard]
  },
  {
    path: 'forget-password',
    component: ForgetPasswordComponent,
    canActivate: [SecureOuterPagesGuard]
  },
  {
    path: 'reset-password',
    component: ResetPasswordComponent,
    canActivate: [SecureOuterPagesGuard]
  },
  {
    path: 'dashboard',
    loadChildren: () => import('./modules/dashboard/dashboard.module').then(m => m.DashboardModule),
    canActivate: [AuthGuard]
  },
  { 
    path: 'internal-server-error', 
    component: InternalServerErrorComponent 
  },
  { 
    path: '**', 
    component: PageNotFoundComponent 
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: []
})
export class AppRoutingModule { }

export const routingComponents = [
  IndexComponent,
  LoginComponent, 
  RegisterComponent,
  ForgetPasswordComponent,
  ResetPasswordComponent,
  SessionTimeOutComponent,
  PageNotFoundComponent
]

Ajax Сервис -

import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map, timeout } from "rxjs/operators";

@Injectable()

export class AjaxService {

  constructor(
    private _http: HttpClient,
  ) { }

  apiCall(
    data: any,
    url: any,
    method: 'DELETE' | 'GET' | 'HEAD' | 'POST' | 'JSONP' | 'PUT',
    isRawUrlFormat: boolean = false
  ){
    // Checking if the provide url is in raw format or not
    if (isRawUrlFormat == false) {
      url = environment.API_URL + "/" + url;
    }

    // creating request variable of type Observable so that any component can subscribe it
    let request: Observable<any>;

     // setting methods of request type and passing params (url, data, headeers and observe to access complete response)
     switch (method) {
      case 'GET':
        request = this._http.get(url, { observe: 'response' });
        break;
      case 'POST':
        request = this._http.post(url, data, { observe: 'response' });
        break;
      case 'PUT':
        request = this._http.put(url, data, { observe: 'response' });
        break;
      default:
        request = this._http.request(method, url, { observe: 'response' });
    }


    // returning api result with status, if found any error returns that error
    return request.pipe(
      timeout(environment.AJAX_TIMEOUT),
      map((apiResult : HttpResponse<any>) => {
        const status : number = apiResult.status;
        let responseObject = apiResult.body;
        responseObject.status = status;
        // if found status 202 means has a refreshtoken in response then again setting it in localstorage
        if (status == 202) {
          localStorage.setItem("userToken", apiResult.body.response.data.token);
        }
        return responseObject;
      })
    )
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...