Angular obtains an undefined response from a service

Having trouble retrieving the data from my service.

Working with Angular 8.

Here's the code snippet:

Within the service:

query(url: string) {
    this.subscription = this.socket$.subscribe(
      (message) => {
        return message;
      },
      (err) => {
        return err;
      },
      () => console.warn('Completed!')
    );
}

Inside the component:

Attempted methods:

fetchDataFromService() {
    var result = this.myservice.query(myurl);
}

The result above returns undefined.

Also tried:

fetchDataFromService() {
    this.myservice.connect(myurl).subscribe
}

However, 'subscribe' is throwing this error:

Property 'subscribe' does not exist on type 'void'.ts(2339)

Is there a way to get the service result without utilizing a promise?

Answer ā„–1

The function named callIt is not returning anything.

Therefore, you are unable to call .subscribe from outside because you are attempting to do so on an undefined variable.

Within the callIt method, you are subscribing to an observable.

If you intend to retain this behavior, consider returning a subscription instead, which does not have a .subscribe method. Alternatively, you can move the subscription logic outside of the callIt method and return the observable instead.

Another option is to still return an observable but utilize pipes to intercept messages, allowing you to subscribe from the external context. This way, you can maintain the logic within your service.callIt function while subscribing externally.


    return this.socket$
        .pipe(tap((message) => console.log(message))
        .pipe(catchError((e) => console.error(e)))
        .pipe(finally(() => console.log('Completed')))

Answer ā„–2

Give this approach a try.

Contact the .service.

invokeFunction(url: string) {
    return this.socket$
}

Contact the .component.

obtainResultFromService() {
    this.myservice.invokeFunction(myurl).subscribe(
      (message) => {
        result = message;
      },
      (err) => {
        console.log('error')
      },
      () => console.warn('Process Completed!')
    );
}

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

Typescript: issue with type guard functionality not functioning properly

type VEvent = { type: "VEVENT"; summary: string; }; type VCalendar = { type: "VCALENDAR"; }; const data: Record<string, VEvent | VCalendar> = (...); array.map((id) => { return { id, title: dat ...

ReactTS: Tips for organizing child components within a "container component"

Currently, I am in the process of developing reusable front-end components in React using Typescript. However, I am encountering a challenge related to a feature commonly found in traditional packages. My goal is to have the ability to nest children of a ...

Retrieving information from Next.js and Typescript with the help of getStaticProps

I've been working on a personal project with Next.js and TypeScript. I'm attempting to fetch data from an API and then map the items, but I'm running into issues. When I use console.log, it returns undefined. The file is located in the pages ...

Upgrade from Angular 7 to the latest version, Angular 8

Here is the content of my package.json file: "@agm/core": "^1.1.0", "@angular/animations": "^8.2.14", "@angular/cdk": "^6.4.7", "@angular/common": "^8.0.0", "@angular/compiler": "^8.2.14", "@angular/core": "^8.2.14", "@angular/forms": "^8.2.14", "@angular ...

AppProps in Next.js - Ensure that you have the correct loader set up to handle this specific file type as there are currently no loaders configured for processing it

I've encountered an issue while working on a Next.JS 13.5.6 application in development mode. When I try to connect to the site, I receive an error message. However, everything works fine when I switch to production mode after building and starting the ...

Unable to retrieve data from the array

I am encountering an issue while trying to fetch data from an array, as I keep receiving undefined Please refer to the image for a visual representation of my problem. I'm not sure what I might be overlooking, so any help would be greatly appreciate ...

Angular2/4 is throwing a 405 error, indicating that the method used is not

updateEmployeeData(ename,ejobtitle,edept,eunit,equal,eaqser,empid) { let url = GlobalVariable.BASE_API_URL + "api/updateEmployeeProfile"; let headers = new Headers({'Content-Type':'application/json'}); let options = new Reque ...

invoke a method from a different class within the same component file

I am facing a situation where I have 2 classes within the same component.ts file. One class is responsible for embedding the Doc blot, while the other class serves as the main component class. I need to call a function that resides in the component class f ...

Selecting the correct data type for react-icons

I'm currently working on designing a navigation bar with a customized type to utilize the map() function. My goal is to display an icon for each entity, so that the icon appears in front of the text within the navbar. However, I am encountering diffic ...

Storing multiple strings in a string array in Angular2

Hi everyone, Iā€™m just getting started with Angular and currently working on creating a recipe page that fetches data from an API. The API setup is complete, but now I need to figure out how to input the data into the API using Angular. I have defined a ...

Steps for transforming 112889 (in mmddyy format) into 11/28/89 or 11/28/1989

Is there a way to convert the unformatted date 112889 (mmddyy) into a specific format like 11/28/89? console.log(new Date('112889')) // The output I'm getting is: Sat Jan 01 112889 00:00:00 GMT+0800 I've searched extensively on Google ...

The function switchMap does not exist in this context

After completing the Angular Tour of Heroes tutorial and some others, I decided to start building apps with Angular 2. One important thing I learned is that when we're listening for changes with a Subject, it's good practice to wait for a few sec ...

The value stored within an object does not automatically refresh when using the useState hook

const increaseOffsetBy24 = () => { setHasMore(false); dispatch(contentList(paramsData)); setParamsData((prevState) => ({ ...prevState, offset: prevState.offset + 24, })); setHasMore(true); }; This function increment ...

A guide on accessing a dynamic object key in array.map()

How can I dynamically return an object key in array.map()? Currently, I am retrieving the maximum value from an array using a specific object key with the following code: Math.max.apply(Math, class.map(function (o) { return o.Students; })); In this code ...

Utilizing Shadow Root and Native Web Components for Seamless In-Page Linking

An illustration of this issue is the <foot-note> custom web component that was developed for my new website, fanaro.io. Normally, in-page linking involves assigning an id to a specific element and then using an <a> with href="#id_name&quo ...

JSDoc encounters issues when processing *.js files that are produced from *.ts files

I am currently working on creating documentation for a straightforward typescript class: export class Address { /** * @param street { string } - excluding building number * @param city { string } - abbreviations like "LA" are acceptable ...

What is the procedure for utilizing custom .d.ts files in an Angular 15 project?

Currently, within my Angular 15 project, I am utilizing a package called bootstrap-italia. This particular package is dependent on the standard Bootstrap package and includes additional custom components and types. However, it should be noted that this pac ...

Launching an Ionic 2 stack app on Heroku is a smooth process

I am currently facing a challenge with deploying my Ionic App. The app's server is deployed on Heroku, but I want to deploy the entire app. However, every tutorial I have come across seems to result in various errors. Here is how my folder structure ...

Why does the Material button style take time to apply when my Angular application first loads instead of being immediate?

Inside the Angular application I'm working on, there is a toolbar component that consists of three different links. The first link directs to the main app page, while the other two lead to distinct components within the app. Each link is styled with c ...

When running `ng build --prod`, an error is thrown indicating that the module does not have

Whenever I try to build in Azure, I encounter an error. However, locally the command 'ng build --prod' works perfectly fine. Error: Module [path_to_file] has no static exports true Since this is for production purposes, I am hesitant to use t ...