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

RouterLink causing component not to reload

In my welcome.component, I have a menu and tab. When I click on a menu item, the routerlink doesn't initiate a new request, causing the tab component not to reload. The tab component is called by multiple router links and should be reloaded every time ...

Angular Material conflicting dependencies

Hello, I am embarking on my journey to learn Angular with Electron. Recently, I forked a repository at the following link: https://github.com/maximegris/angular-electron However, I have encountered a challenging dependency issue: ✘ daniel@daniel-HP-ZBoo ...

Tips for concealing a chosen alternative from the menu of options when utilizing mat-select

I am currently working with the latest version of mat-select, version 16. I have a requirement where, when a specific option is selected and the select drop-down is clicked again, that selected option should not appear in the options list. Below is the HTM ...

Unable to bring in CSS module in a .tsx file

I am currently working on a basic React application with TypeScript, but I am encountering difficulty when trying to import a CSS file into my index.tsx file. I have successfully imported the index.css file using this method: import './index.css&apo ...

Show variously colored information for each selection from the dropdown using Angular Material

I am trying to change the color of displayed content based on user selection in an Angular application. Specifically, when a user chooses an option from a dropdown list, I want the displayed text to reflect their choice by changing colors. For example, i ...

Preventing duplicate actions on a Subject with Angular 7's rxjs debounceTime operator

While working on an Angular7 application, I encountered an issue where the KeyUp event of a numeric input was being captured by this specific HTML code: <input fxFlex type="number" formControlName="DM" (keyup)="changeDM()"> </div& ...

Are you looking to use the 'any' type instead of the 'Object' type? Angular Services can help you with that

I encountered the following error message: Argument of type 'OperatorFunction<APISearch[], APISearch[]>' is not assignable to >parameter of type 'OperatorFunction<Object, APISearch[]>'. The 'Object' type is ...

When two-dimensional arrays meet destructuring, it results in a type error

Can anyone clarify TypeScript behavior in this scenario? JavaScript const test1 = [ ['a', 'b'], ['c', 'd'], ]; const test2 = [ ...[ ['a', 'b'], ['c', ' ...

Printing the HTML Template of a widget with multiple loops results in a blank first page being displayed

I have encountered an issue while working with a table and ng-repeat loops in my report widget. The table displays fine on the screen, but when I try to print it, there is always a blank page at the beginning. Interestingly, if I remove the second and thir ...

I need help differentiating "namespace" from "static attributes" in TypeScript

Separating namespace from static properties in TypeScript can sometimes be tricky. error: 'ClassA' only refers to a type, but is being used as a namespace here. class ClassA { static ClassB = class { }; } type T = ClassA // ok type T = C ...

Extract objects from a nested array using a specific identifier

In order to obtain data from a nested array of objects using a specific ID, I am facing challenges. My goal is to retrieve this data so that I can utilize it in Angular Gridster 2. Although I have attempted using array.filter, I have struggled to achieve t ...

I recently used the ng new ang-routing command to generate a fresh Angular project in my directory, but encountered an error while doing so

npm ERR! syscall read npm ERR! errno ECONNRESET npm ERR! network Invalid response body while trying to fetch https://registry.npmjs.org/@angular-devkit%2fbuild-angular: read ECONNRESET npm ERR! network This issue is likely caused by connectivity problems. ...

sending additional query parameters with an HTTP request

I am in need of making an API call that allows me to include optional query string parameters. retrieveConts(param1:string,param2?:string):Observable<IContracts> { this.basePath = "/myConts"; return http.get(this.basePath,{ param ...

Incorporate an image icon into an Angular grid

Currently, I am in the process of building a web application using Angular. The main goal is to create a grid and color specific cells based on data input. Below is the snippet of my HTML code: <mat-grid-list cols="10"> <mat-grid-tile * ...

Angular Kendo Grid (version 1.4.1)

I am currently encountering an issue where I want to select the first row in a Kendo Grid. Here is the code snippet that I have implemented: In my Component file: export class SampleComponent{ gridView: GridDataResult; mySelection: number[] = [0]; ...

Navigating the complexities of extracting and storing a data type from a collection of objects

Dealing with a messy API that returns inconsistent values is quite challenging. Instead of manually creating types for each entry, I am looking for a way to infer the types programmatically. One approach could be by analyzing an array like this: const arr ...

How come TypeScript does not generate an error when attempting to import a default export that does not exist?

As I work on converting my code from non-TypeScript CommonJS files to TypeScript ES6 modules, I encountered an issue with the import statements. Specifically, I needed to use import * as x instead of import x: The original snippet looked like this: const ...

What is the best way to grasp the connections between the any, unknown, {} data types and their relationships with other types?

Seeking to comprehend relationships between different types, the following code is presented: type CheckIfExtends<A, B> = A extends B ? true : false; type T1 = CheckIfExtends<number, unknown>; //true type T2 = CheckIfExtends<number, {}> ...

Unveiling a node through code in the angular tree component

Struggling to figure out a simple task using the angular-tree-component - given how amazing the component is, I'm sure it's something straightforward in the API that I am missing. I am trying to dynamically display a node by expanding all its pa ...

Managing the closest element depending on the selected option in Angular 5

My task involves accessing the nearest element of a dropdown. The HTML below includes multiple dropdowns and input boxes. When selecting options from the dropdown, I need to enable or disable the input box closest to it. <div class="form-block" *ngFor= ...