The service seems to be encountering an issue with the "message" object. Even though property values are assigned using the "add()" method, accessing these properties directly from the component or through a getter still returns undefined values. This discrepancy has been confirmed by the log() method within the getter function.
As someone who is new to Angular and TypeScript, I may not be able to spot an obvious mistake. Any help in resolving this issue would be greatly appreciated.
Message object:
export class Message {
messageText: string;
messageStatus: MessageStatus;
}
MessageStatus enum:
export enum MessageStatus {
INFO,
SUCCESS,
ERROR,
WARN
}
Service:
import {Injectable} from '@angular/core';
import {Message} from '../../model/message';
import {log} from 'util';
@Injectable({
providedIn: 'root'
})
export class MessageService {
private message: Message = new Message();
constructor() { }
public add(message: Message): void {
this.message = message
log('MESSAGE in add: ' + this.message.messageText +', STATUS in add: ' + this.message.messageStatus);
}
public getMessage(): Message {
log('MESSAGE in get: ' + this.message.messageText +', STATUS in get: ' + this.message.messageStatus);
return this.message;
}
public clear(): void {
this.message = new Message();
}
}
Component:
import { Component, OnInit } from '@angular/core';
import {MessageService} from '../../service/messages/message.service';
import {MessageStatus} from '../../service/messages/messageStatus';
@Component({
selector: 'app-messages',
template: `
<div class="message-position" *ngIf="messageService.getMessage().messageText">
<div [ngClass]="{
'alert alert-info': messageService.getMessage().messageStatus === MessageStatus.INFO,
'alert alert-success': messageService.getMessage().messageStatus === MessageStatus.SUCCESS,
'alert alert-danger': messageService.getMessage().messageStatus === MessageStatus.ERROR,
'alert alert-warning': messageService.getMessage().messageStatus === MessageStatus.WARN
}">
{{messageService.getMessage().messageText}}
<button class="btn btn-primary" (click)="messageService.clear()">Ok</button>
</div>
</div>`,
styleUrls: ['./messages.component.scss']
})
export class MessagesComponent{
constructor(public messageService: MessageService) { }
}
The log() output in the add() method confirms that the object properties have received values:
25 Nov 19:05:22 - MESSAGE in add: Customer not found, STATUS in add: 3
However, the log() output in the getMessage() method continues to show that the object properties remain undefined:
25 Nov 19:05:22 - MESSAGE in get: undefined, STATUS in get: undefined
UPDATE:
The method calling the add() method is located in a different class:
private messageService: MessageService = new MessageService();
private message: Message = new Message();
logResponce(messageText: string, messageStatus: MessageStatus): void {
this.message.messageText = messageText;
this.message.messageStatus = messageStatus;
this.messageService.add(this.message);
}