es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Indefinido: incluir un servicio dentro de otro servicio – Angular 2

Mi Servicio de Notificaciones está incluido en mi Servicio Global pero cuando llamo a cualquier función del Servicio de Notificaciones, muestra el siguiente mensaje: No se pueden leer las propiedades de undefined (leyendo ‘warn’). ¿Qué estoy haciendo mal? Creo que está relacionado con problemas de alcance.

Aquí está mi código de Servicio de Notificaciones:

import { Injectable } from '@angular/core';
import { MatSnackBar, MatSnackBarConfig } from '@angular/material/snack-bar';

@Injectable({
  providedIn: 'root'
})
export class NotificationService {

  constructor(public snackBar: MatSnackBar) { }

  config: MatSnackBarConfig = {
    duration: 3000,
    horizontalPosition: 'right',
    verticalPosition: 'bottom'
  };

  warn(msg: string): void {
    this.config['panelClass'] = ['notification', 'warn'];
    this.snackBar.open(msg, '', this.config);
  }

}

Aquí está mi código de Servicio Global:

import { Injectable } from '@angular/core';
import { HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { throwError } from 'rxjs/internal/observable/throwError';
import { NotificationService } from '@services/notification.service';

@Injectable({
  providedIn: 'root'
})
export class GlobalService {

  constructor(private notification_srv: NotificationService) { }

  public handleError(error: HttpErrorResponse) {
    if (error.status === 0) {
      console.error('An error occurred:', error.error);
      this.notification_srv.warn(`An error occurred: ${error.error}`);
    } else {
      console.error(
        `Backend returned code ${error.status}, body was:`, error.error);
      this.notification_srv.warn('Backend returned code');
    }
    return throwError('Something bad happened; please try again later.');
  }
}
Tags:  , , ,

Answer

  1. Avatar for davy.ai

    El problema probablemente se debe al alcance del objeto NotificationService que no está definido correctamente. En el constructor de GlobalService, estás inyectando NotificationService, pero es posible que no se haya instanciado todavía cuando se ejecuta el método handleError.

    Una forma de solucionar este problema sería asegurarse de que el NotificationService también se proporcione en el archivo app.module.ts además de GlobalService. Esto garantiza que solo haya una instancia del servicio en toda la aplicación y que se instancie correctamente antes de ser llamado en GlobalService.

    Otra solución sería utilizar el gancho de ciclo de vida ngOnInit en GlobalService para asegurarse de que NotificationService se instancie antes de ser utilizado en el método handleError.

    import { Injectable, OnInit } from '@angular/core';
    import { HttpErrorResponse } from '@angular/common/http';
    import { throwError } from 'rxjs';
    import { NotificationService } from '@services/notification.service';
    
    @Injectable({
      providedIn: 'root'
    })
    export class GlobalService implements OnInit {
    
      constructor(private notification_srv: NotificationService) { }
    
      ngOnInit(): void {
        // Realizar alguna inicialización aquí
      }
    
      public handleError(error: HttpErrorResponse) {
        if (error.status === 0) {
          console.error('Ocurrió un error:', error.error);
          this.notification_srv.warn(`Ocurrió un error: ${error.error}`)
        } else {
          console.error(`El servidor devolvió el código ${error.status}, el cuerpo fue: `, error.error);
          this.notification_srv.warn('El servidor devolvió el código')
        }
        return throwError('Algo salió mal; por favor, inténtelo de nuevo más tarde.');
      }
    }
    

    Cualquiera de estas soluciones debería solucionar el problema con el alcance del objeto NotificationService.

Comments are closed.