You cannot assign type void to type any

I'm currently working on a component that involves some code:

export class AddNewCardComponent { 

    public concept = [];
    constructor( 
        private _router: Router,
        private _empDiscService: empDiscService) { 

        }

    ngOnInit(){
        this.concept = this._empDiscService.StoreMaster()
        .subscribe((data)=>{
            this.concept =  data;
        });
    }
}

The main purpose is to retrieve a variable from the services and store it in my array called "store". However, I encountered an issue where:

type void is not assignable to type any

Here's the snippet of my service code:

import {Injectable} from '@angular/core';
import { Httpprovider } from './httpprovider';

@Injectable()
export class empDiscService{

    public storedata = [];
    constructor(private _httpprovider: Httpprovider){

    }

    StoreMaster():Observable<any[]>{
        return this._httpprovider.httpReq('http://192.168.1.40:5000/getconcept','GET',null,null).map(res =>{<any[]>res.json()}
    };
}

Answer №1

import { JobService } from './../services/job.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-job-list',
  templateUrl: './job-list.component.html',
  styleUrls: ['./job-list.component.css']
})
export class JobListComponent implements OnInit {

 **jobs:any = [];**
error = '';
constructor( private jobservice:JobService) { }

ngOnInit() {
this.jobservice.getJobs().subscribe(

data => this.jobs = data,
error => {console.log ('error')}

);


}

}

Answer №2

When working with RxJs, it is important not to call the subscribe() method inside the service and instead return the object directly.

export class EmployeeDiscountService{

    public storedData = [];
    constructor(private _httpProvider: HttpProvider){

    }
    retrieveMasterData(): Observable<any[]>{
       return this._httpProvider.httpReq('http://192.168.1.40:5000/getmapmasterstore','GET',null,null).map(res =>{<any[]>res.json()}
    }

}

Your component setup should look like this:

constructor( 
        private _router: Router,
        private _employeeDiscountService: EmployeeDiscountService) { 
          this.store = this._employeeDiscountService.retrieveMasterData()
            .subscribe((data)=>{
                    this.storedData =  data;
        });
}

The mistake in your code was that the service method was not returning anything.

retrieveMasterData():Observable<any[]>{}

By making this change, you will fix the issue you were encountering.

Answer №3

StoreMaster() function does not have a return value. It may be necessary to modify the service method to return an observable:

StoreMaster(){
return this._httpprovider.httpReq('http://192.168.1.40:5000/getmapmasterstore','' +
  '  GET',null,null).subscribe((data)=>{
  var brData = [];
  for (let i=0;i<data.length;i++){
    brData.push(data[i]);
  }
  return brData;
});
}

and ngOnInit

    ngOnInit(){
        this._empDiscService.StoreMaster()
            .subscribe(store => this.store = store);
    }

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

Differences between Typescript Import and JavaScript import

/module/c.js, attempting to export name and age. export const name = 'string1'; export const age = 43; In b.ts, I'm trying to import the variables name and age from this .ts file import { name, age } from "./module/c"; console.log(name, ...

`I'm having difficulty transferring the project to Typescript paths`

I posted a question earlier today about using paths in TypeScript. Now I'm attempting to apply this specific project utilizing that method. My first step is cloning it: git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Having trouble populating and submitting a selected option from a dropdown menu in Angular?

Upon loading the page, the Category dropdown automatically populates with data from the database. However, when I attempt to select a value from the dropdown and click a button to post the data to a specified URL, an error occurs: ERROR Error: Error tryin ...

Tips for managing Typescript Generics while utilizing the styled function provided by the '@mui/material/styles' package

import Table,{TableProps} from 'my/table/path' const StyledTable = styled(Table)({ ...my styles }) const CustomTable = <T, H>(props: TableProps<T, H>) => { return <StyledTable {...props} /> } This is the issue I encoun ...

Tips for preventing CORS and SSL issues when using localhost

Attempting to log in with Google on my Svelte app involves sending a request to an Express server. However, I encounter different errors on different browsers. On Firefox, I receive a Cross-Origin Request Blocked: The Same Origin Policy disallows reading t ...

The term 'shuterstock_init' is meant to be a type, however, it is mistakenly being treated as a value in this context

I am working on a service called class imageService, which mainly consists of key value pairs export type servicesName = "unsplash" | "pexels" | "pixabay" | 'shutterstock'; export type Service = { [key in services ...

What is the process of incorporating a custom data type with ngModel in Angular Dart?

In the process of developing an app using AngularDart, I have come across some interesting challenges. While I appreciate the ease with which forms can be handled in AngularDart, I am facing a hurdle when it comes to working with different data types. My ...

Discover a more efficient method for expanding multiple interfaces

Hey there, I'm having some trouble with TypeScript and generics. Is there a better way to structure the following code for optimal cleanliness and efficiency? export interface Fruit { colour: string; age: number; edible: boolean; } export inte ...

Issue with Angular 7 Universal: components inside are failing to display

I have successfully implemented Angular 7 Universal with dynamic server-side rendering. However, I am facing an issue where dynamic components within the main component being rendered on the server are not rendered themselves. Here is an example of the re ...

Develop a TypeScript class that includes only a single calculated attribute

Is it advisable to create a class solely for one computed property as a key in order to manage the JSON response? I am faced with an issue where I need to create a blog post. There are 3 variations to choose from: A) Blog Post EN B) Blog Post GER C) Bl ...

Turning slide toggle on and off in Angular Material: A step-by-step guide

I am facing an issue where I have a list of mat slide toggles generated using a for loop. My goal is to disable all other slide toggles when one is clicked. Here is my code: HTML: <div class="row"> <div class="col-md-6 mt-2" *ngFor="let data ...

Issues with Angular Form Builder's Form Control not updating when invalid, causing errors with ngIf statements

I am encountering an issue where the error division fails to appear when the validator is invalid. The problem seems to be originating from this line: <div class = "danger" *ngIf="firstName?.invalid && (firstName?.dirty || firstName?.touched) ...

Effortlessly bring in Typescript namespace from specific namespace/type NPM package within a mono-repository

Instead of repeatedly copying Typescript types from one project to another, I have created a private NPM package with all the shared types under a Typescript namespace. Each project installs this NPM package if it uses the shared types. index.d.ts export ...

The border of the Material UI Toggle Button is not appearing

There seems to be an issue with the left border not appearing in the toggle bar below that I created using MuiToggleButton. Any idea what could be causing this? Thank you in advance. view image here view image here Just a note: it works correctly in the ...

Having an empty string in an array used with *ngFor can lead to unusual positioning problems, unlike when the array contains non-empty strings

Check out this live demo to see it in action: https://stackblitz.com/edit/angular-5vwspd You might notice that the first 2 days are positioned strangely on the calendar. I'm currently working on a calendar component, and I am using an array called d ...

AWS Lambda serverless deployment of Angular Universal is failing to detect javascript files in the dist/browser directory

After following the steps in this tutorial for deploying to a lambda function, I encountered some issues. When testing it using serverless offline, I kept getting 404 errors for each compiled JS file. However, once I deployed it, the errors changed to 403. ...

This error message indicates that the certificate for Angular 13 has expired

After successfully installing Angular and verifying the version, I encountered an issue when attempting to run the command npm start. Despite multiple attempts at uninstalling and reinstalling everything, the problem persists. Running npm install also resu ...

Reactive Programming: Transforming an earlier value as it moves down the pipeline

In a recent project, I encountered an interesting scenario involving the execution of multiple requests in a pipe chain. This specific case revolves around the display of images within the quill text editor. The backend returns the content in the followin ...

Unit Testing in Vue.JS: The original function remains active even after using sinon.stub()

While unit testing my components (which are coded using TypeScript along with vue-class-component), I am utilizing Sinon to stub API calls. However, even after adding the stub to the test, the original method is still being invoked instead of returning the ...

"Enhancing the appearance of mat-sidenav elements in Angular Material 7 with customized

Our previous dom-structure before upgrading to Angular 7 and Material 7 looked like this: <mat-sidenav-container> <mat-sidenav #sidenav mode="side" [opened]="sideNavOpen"> <ul> <li> <a mat-icon-button color ...