Mike
Mike

Reputation: 93

How to properly override a method in a service that is inherited from a service that uses observable?

I want to override the add method of the MessagingService.
For this, I create my own MsgService that extends the MessagingService:

@Injectable({
    providedIn: 'root'
})
export class MsgService extends MessageService {
    constructor() {
        super();
    }

    public add(msg: Message) {
        console.log(msg);
        super.add(msg);        
    }
}

I see confirmation in the console that the method is being called, but the message itself does not appear.
Messagservice uses Observable and under the debugger I see that the observers array is empty:

enter image description here

Can someone explain why this is happening and how to properly override a method in an inherited service?

Upvotes: 0

Views: 1288

Answers (1)

Aakash Garg
Aakash Garg

Reputation: 10979

This is how your component should look to override service class :-

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  providers: [
    {
      provide: MessageService,
      useClass: MsgService
    }
  ]
})
export class AppComponent {
  // constructor(private messageService: MessageService, private primengConfig: PrimeNGConfig) {}
  constructor(
    private messageService: MessageService,
    private primengConfig: PrimeNGConfig
  ) {}

  ngOnInit() {
    this.primengConfig.ripple = true;
  }

  showViaService() {
    this.messageService.add({
      severity: 'success',
      summary: 'Service Message',
      detail: 'Via MessageService'
    });
  }
}

Working Stackblitz :- https://stackblitz.com/edit/primeng-messages-demo-qukwyz?file=src/app/app.component.ts

Upvotes: 1

Related Questions