Unable to set values to properties of an object within an Angular service

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);
  }

Answer №1

initialize MessageService()

This method initializes a new MessageService object. However, it is recommended to utilize the singleton instance provided by Angular and automatically injected into the component.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Endpoint path for reverse matching in Mongodb API

I am currently in the process of setting up a webhook system that allows users to connect to any method on my express server by specifying a method and an endpoint to listen to (for example PUT /movies/*). This setup will then send the updated movie to the ...

Designing the Firebase Structure of an Angular Application

What is the best way to structure Firestore and Angular for efficient querying? When using a JSON Cloud Firestore database, one of the challenges is inserting people and relating them to users. To optimize query speed and efficiency, it is important to c ...

All constructors at the base level must share a common return type

I am looking to convert my JSX code to TSX. I have a snippet that refactors a method from the react-bootstrap library: import {Panel} from 'react-bootstrap'; class CustomPanel extends Panel { constructor(props, context) { super(props ...

Angular2 is failing to display the ChildComponent selector

I want to present information in an HTML table, and I've decided to create a separate component for the <tr> tag since it will be repeated multiple times with some logic. However, when I try to render this child component within the <tbody&g ...

The @Input default value is being replaced by `undefined` within the testing environment

Within my component, I have the following input: @Input() someThing: string = 'm'; // default value When testing, I defined it as follows: @Component({ selector: 'app-test-wrapper-component', template: ` <app-my-component so ...

Prefer utilizing Null over Undefined

In my Angular 7 application, I have defined the following interface: export interface Request { limit?: number; offset?: number; } Additionally, there is a service method implemented like so: public get(request: Request): Observable<Response>& ...

Unveiling the secrets of the Google Region Lookup API

I am struggling to incorporate the Region Area Lookup feature from Google Maps into my project. Despite it being an experimental feature, I am having difficulty getting it to function correctly. Initially, I attempted to integrate this feature into a Reac ...

Tips on extending the response wait time for an API request using Observable RxJS in Angular

I have a Java Spring Boot backend application and an Angular frontend. In my front end, I am using a REST API to delete a file on the server but I keep getting a 404 error even though the service has been consumed and finished correctly. I suspect that th ...

Angular Navbar-Toogle Not Functioning with Bootstrap 5

I encountered an error on my console related to Popper.js. Specifically, I am receiving the following error message: "scripts.js:7 Uncaught SyntaxError: Unexpected token 'export'." Due to this error, I suspect that my toggle button is not functio ...

Bringing tex2max.js into an angular application using npm and index.html

Every time I attempt to import tex2max with the command declare var tex2max: any;, I encounter a ReferenceError: tex2max is not defined. Interestingly, this issue does not arise with other npm packages. Despite trying various methods such as installing the ...

Use Angularfire 5 to merge data from multiple lists based on a common key

Ever since the release of Angularfire5, using $key has become a thing of the past. I decided to convert this and stumbled upon a snippet that shows how to change the list into one containing their own key: getRankings(week): Observable<any> { ...

The declaration file for module 'vue-tabulator' was nowhere to be found

Trying to incorporate the vue-tabulator Vue component from https://github.com/angeliski/vue-tabulator into a basic Vue application written in TypeScript. main.ts: import Vue from 'vue' import VueTabulator from 'vue-tabulator' import A ...

"Unfortunately, Azure Web Static Apps do not have the capability to access .env files that are prefixed with NEXT

Suppose I have an .env file set up like this: NEXT_PUBLIC_API_BASE_PATH = value1 While this .env is functioning correctly in my local environment, once deployed to Azure Web Static Apps and added to the configurationhttps://i.sstatic.net/eqiYn.png My app ...

Error loading the app.html file

Whenever I include templateUrl in the @Component section, an error pops up in the browser console. @Component({ selector: 'http-app', directives: [ ], templateUrl: "app.html", }) class HttpApp { } Error: Uncaught (in promise): Failed t ...

Encountered an issue: The type 'Usersinterface' is not meeting the document constraints

Below is a screenshot displaying an error: https://i.stack.imgur.com/VYzT1.png The code for the usersinterface is as follows: export class Usersinterface { readonly username: string; readonly password: string; } Next, here is the code for users ...

Error TS2604: Upon importing the 'material-ui' button from one package into another

Our team is in the process of implementing a new front-end for our application by transitioning from standard react to typescript. As someone who is relatively new to development, I have been struggling with a particular issue for several days now. The set ...

Lerna: The Ultimate Guide to Installing External Packages Across Multiple Projects

We utilize Lerna for managing our mono-repo projects, and I am seeking the most effective method to install an external package in my projects while ensuring they all use the same version. Here is my project structure (my-Main-A and my my-Main-B both depe ...

What steps should be taken to prepare data for transmission to a server in a Next.js environment?

I'm in the process of creating a website that requires authentication. I am using Next (React) and typescript for web development. My objective is to make most pages ServerSideRendered or StaticHTML. However, I encountered an issue right at the begin ...

TypeScript Vue Component with Generics

I'm currently trying to provide a generic type in a Vue component, but I'm unsure of how to do this from the caller. Take the following component as an example: export default class Toggle<T> extends Vue { @Prop({ default: {} }) pr ...

Tips for accessing data in Angular 2

When utilizing the post method, the following code is used in the ts file: viewt(testid) { $('#myModal22').modal('show'); var param2 = { testid:testid, } this.service.get_tquestion(param2).subscribe(data => { ...