The issue of ownership is not present in this type

Encountered an issue during compilation indicating that a class is missing a property when accessed from the component, even though the call is successful.

Here is the class in question:

    export declare class MessageService {
    private messageSource;
    private clearSource;
    messageObserver: import("rxjs/internal/Observable").Observable<Message | Message[]>;
    clearObserver: import("rxjs/internal/Observable").Observable<string>;
   public  add(message: Message): void;
   public addAll(messages: Message[]): void;
    clear(key?: string): void;
}

And this is how it's being called from the component:

showSuccess(details) {
    this.messageService.add({ severity: 'success', life: 5000, summary: 'Success Message', detail: details });        
}

Compilation resulted in warnings.

ERROR in C:/Users/..../webapp/app/entities/asset/asset-update.component.ts(555,29):
TS2339: Property 'add' does not exist on type 'MessageService'.

Contents of messageService.js :

"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
var rxjs_1 = require("rxjs");
var MessageService = /** @class */ (function () {
    function MessageService() {
        this.messageSource = new rxjs_1.Subject();
        this.clearSource = new rxjs_1.Subject();
        this.messageObserver = this.messageSource.asObservable();
        this.clearObserver = this.clearSource.asObservable();
    }
    MessageService.prototype.add = function (message) {
        if (message) {
            this.messageSource.next(message);
        }
    };
    MessageService.prototype.addAll = function (messages) {
        if (messages && messages.length) {
            this.messageSource.next(messages);
        }
    };
    MessageService.prototype.clear = function (key) {
        this.clearSource.next(key || null);
    };
    MessageService = __decorate([
        core_1.Injectable()
    ], MessageService);
    return MessageService;
}());
exports.MessageService = MessageService;
//# sourceMappingURL=messageservice.js.map

Answer №1

When dealing with a regular class, the instantiation process is essential and should be done in the following manner:

public messageService: MessageService = new MessageService();

However, if you are working with a service that is decorated with @Injectable(), it must be registered within the module. Then, to utilize the service, it needs to be provided in the constructor of your component like so:

constructor(private messageService: MessageService) {...}

By following this approach, all public properties of the class will be easily accessible.

UPDATE: It is worth noting that the add method should ideally be implemented inside the MessageService class for proper functionality. Instead of having it defined like this:

public  add(message: Message): void;

You should consider implementing it as follows:

public add(message: Message): void {
    // Perform actions on the message received...
    this.messages.push(message);
}

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

Unknown Element Error in Angular

Currently, I am working with Angular and Electron. I have successfully included ngx-quill in my module file. @NgModule({ imports: [ ~~~, QuillModule ], exports: [RouterModule] }) In addition, I have imported Quill into my main component file im ...

When working with Typescript, encountering difficulty in locating or importing modules from a parent directory that is one level above the tsconfig.json file is

My project's directory structure looks like this: Main/project-root/* (tsconfig.json, packages.json, app.ts, etc are located here) Main/shared/* (shared.ts is located here along with other ts files, no packages.json or any other files) Let's ...

Exploring the relationship between two entities in Angular 7 using Typescript

Creating a Reactive form for user registration in Angular involves setting up the form data object separately from the viewmodel object. https://i.sstatic.net/ERlYa.png export interface RegisterViewModel { UserName: string; Email: string; Password: strin ...

How can I fix the error "Type '() => void' does not have property 'push'" in Typescript for Angular 10?

I encountered an issue while using push() on an array in an Angular 10 project written in Typescript. Error Property 'push' does not exist on type '() => void'.ts(2339) I need assistance in understanding why this error is occurring ...

Processing Data with JavaScript

I am new to working with JavaScript, coming from the Python world. I need some assistance. Currently, I am retrieving data from the back end that has the following structure: { "Airports": { "BCN": { "Arrivals": [ ...

Strategies for managing a blank starting state in Redux that will be filled in at a later time

I am currently facing an issue while working with redux in TypeScript. Initially, my state is an empty object {} and later it gets populated with keys and values. However, when I attempt to use this state in my component, I encounter the error this propert ...

Implementing a filter function in Angular 2 and Ionic 2 that is dependent on *ngFor on a separate page

I recently created a simple ion-list along with a filter to display items based on a specific key:value pair. I'm not entirely sure if I've implemented it correctly, so any suggestions on a better approach would be greatly appreciated. LIST.HTML ...

Adjust website content depending on user's authentication status

My goal is to display a logout button when the user is logged in and a login button if they are not. I am using JSON tokens to determine if a user is logged in or not, by checking if the token is null. However, this approach does not seem to be working. Ca ...

Navigating JSON data in a POST request using C# in .NET Core version 3.1

Previously, in my .Net Core 2.1 project, I had implemented a method to handle JSON data successfully as shown below: [HttpPost] [Route("sendJsonData")] public JObject saveTemplate(JObject jsonString) { string templateName = (string)jsonString.Sel ...

How to Customize Bootstrap Colors Globally in Angular 4 Using Code

I am interested in developing a dynamic coloring system using Angular. I have set up a service with four predefined strings: success, info, warning, and danger, each assigned default color codes. My goal is to inject this service at the root of my applicat ...

Steps for enabling a function to return an undefined type

After extensive review, I have discovered that TypeScript has numerous hidden nuances, which make it less strict and accurate. I prefer to utilize 'undefined' as the return type for functions because it accurately reflects the reality of the sit ...

Mistakes encountered following the installation of lodash in Angular 2

After adding lodash to my Angular 2 project, I encountered a significant number of errors. To troubleshoot, I created a new project using the CLI: ng new tester, then I added lodash with npm install --save @types/lodash. When I ran ng serve, I received the ...

Improving Angular component performance with a multitude of subcomponents

Some time back, I created a grid component for an Angular application. Each Grid consists of rows represented by Row components, and each Row contains cells that are also components called Cell. These cells can hold various "objects" which are essentially ...

Encountering an undefined property error while using Array.filter in Angular 2

hello everyone, I am currently faced with an issue while working on a project that involves filtering JSON data. When using the developer tools in Chrome, it keeps showing me an error related to undefined property. chart: JsonChart[] = []; charts: JsonC ...

Is it just me, or does the this.router.subscribe method no longer exist in Angular 2's @angular/router library?

I'm experiencing an issue in Angular 2 with the library @angular/router. It appears that the method this.router.subscribe no longer exists. Previously, this code worked fine on an older version of the router that has since been deprecated. Does anyon ...

Commitments shatter amidst constructing a website

Utilizing promise and http.get to retrieve data from a JSON API in Wordpress. Once the data is retrieved, it should be displayed on a page... However, an error occurs when attempting to build the page due to the data not being available. What steps can ...

Combining results from multiple subscriptions in RxJS leads to a TypeScript compiler error

I am utilizing an Angular service that provides a filterObservable. To combine multiple calls, I am using Rx.Observable.zip(). Although it functions as expected, my TypeScript compiler is throwing an error for the method: error TS2346: Supplied paramete ...

The mat-datepicker appears in a unique location each time it is opened

I am facing an issue with my mat-datepicker appearing in the opposite place when clicked on one component. How can I resolve this? I have two different components with mat-datepicker, but they behave differently. I suspect that imitating a click in one com ...

Communication among sub applications is crucial for the success of Micro Frontends

After researching the best practices for frontend applications, I made the decision to refactor our monolith application. Instead of choosing between micro frontends and mono repo approaches, I decided to merge them both in a unique way. I plan to create ...

Adding a dynamic component to a directive in Angular 2.1

As a newcomer to Angular 2.1, I am looking to spruce up some elements for automatic translation using a custom directive. The syntax I have in mind is: <span customDirectiveTranslation="translateble">{{translateble}}</span> or simply <spa ...