I am interested in transforming an Angular 2 observable into a custom class

Having recently delved into the world of angular2, I've spent countless hours trying to tackle a particular challenge without success. My goal is to convert an observable from an HTTP call and store it in a class.

Below are the key components involved:

The JSON file:

[{
    "nickname": "magicMike",
    "id": "123",
    "name": "Michael",
    "nachname": "Fischer",
    "pictURL": "../images/mainPanel/Image_dummy.jpg",
    "city": "Ulm"
}]

The user class file:

export class User {

  nickname: string;
  id: string;
  name: string;
  nachname: string;
  pictURL: string;
  city: string;


  constructor(
    nickname: string,
     id: string,
     name: string,
     nachname: string,
     pictURL: string,
     city: string
  ){
    this.nickname = nickname;
    this.id = id;
    this.name = name;
    this.nachname = nachname;
    this.pictURL = pictURL;
    this.city = city;
  }
}

The service responsible for reading the JSON file:

import { Component, Input } from '@angular/core';
import { Injectable }     from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { User } from './user'

@Injectable()
export class UserService {
   user: Array<User>;
  private useUrl = '/json/user.json';
  constructor(private http: Http) {

  }



  getUser(): Observable<any> {
    return this.http.get(this.useUrl)
      .map(this.extractData)
      .do(data => console.log("User from json: " + JSON.stringify(data)))
      .catch(this.handleError);
  }

  private extractData(response: Response) {
    let body = response.json();
    return body || {};
  }


  private handleError(error: Response) {
    console.log(error);
    return Observable.throw(error.json().error || "500 internal server error");
  }

The component that receives the observable and stores it in an array:

   .......
export class AppComponent implements OnInit {


      public user: User[];

     ngOnInit() {
        this.userService.getUser()
          .map((user: Array<any>) => {
            let result:Array<User> = [];
            if (user) {
              user.forEach((erg) => {
                result.push(new User(erg.nickname, erg.id, erg.name, erg.nachname, erg.pictURL, erg.city ));
              });
              }

            })
          .subscribe(user => this.user = user);
      }
....

However, upon running this code, I encounter the following error:

C:/Users/Lenovo/Documents/ui-challenger.one/src/app/app.component.ts (53,26): Type 'void' is not assignable to type 'User[]'.)

I'm reaching out in hopes that someone can offer assistance. All I aim to achieve is parsing a JSON file into a class so that I can access properties like "User.name".

Answer №1

 Initializing user data in ngOnInit() function:
    this.userService.getUser()
      .map((user: Array<any>) => {
        let result:Array<User> = [];
        if (user) {
          user.forEach((erg) => {
            result.push(new User(erg.nickname, erg.id, erg.name, erg.nachname, erg.pictURL, erg.city ));
          });
        }
        return result; // <<<=== ensure to include the return statement
      })
      .subscribe(user => this.user = user);
  }

Answer №2

No need to parse JSON manually into an Object anymore. You can achieve the same result by following this approach:

 fetchUser(): Observable<User[]> {
    return this.http.get(this.userUrl)
      .map(response => <User[]> response);
  }

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

Searching Firestore arrays for objects based on one of two fields

Within my document, I am working with the following array: https://i.sstatic.net/j9hBT.png I have a SizeFilterComponent that emits a BaseFilter object when a size is selected. Multiple sizes can be selected. Here is the method handling this logic: selecti ...

What is the most effective way to use a withLatestFrom within an effect when integrating a selector with props (MemoizedSelectorWithProps) sourced from the action?

I am struggling to utilize a selector with props (of type MemoizedSelectorWithProps) in an effect inside WithLatestFrom. The issue arises because the parameter for the selector (the props) is derived from the action payload, making it difficult for withLat ...

The error message "Can't resolve all parameters for CustomerService" is preventing Angular from injecting HttpClient

I have a customerService where I am attempting to inject httpClient. The error occurs on the line where I commented //error happens on this line. Everything works fine until I try to inject httpClient into my service. The error message is: `compiler.js: ...

Ways to adjust the color dynamics of a mat-slider

I am looking to dynamically change the color of a mat-slider. In my app, users have the ability to select any color from a color palette, and I want to display that selected color as the slider color. While I know you can add custom color names in the col ...

Encountering errors while running Angular 8's ng build prod command

After successfully migrating my project from Angular 7 to Angular 8, I encountered an issue when attempting to run 'ng build prod' which resulted in the following error: ERROR in Error during template compile of 'Ng2CompleterModule' Cou ...

The `finally` function in promises is failing to execute properly

Currently working with Typescript and I've included import 'promise.prototype.finally' at the beginning of my index.js file (in fact, I've added it in multiple places). Whenever I try to use a promise, I encounter the error message say ...

Contrasting @Input with Dependency Injection in Angular 10

Is there a way to pass values from a parent component to a child component without using the @Input decorator? I'm thinking about creating an instance of the Parent class in the constructor (Dependency Injection) and then accessing the variable value ...

Collaborate on a component used in multiple modules

In my application, there are two modules: employer and landing. I have created a component in the landing module that I want to share with the employer module. To achieve this, I declared the component in the app.module.ts file of the parent module and use ...

Clicking on the sub kendo panelbar item activates the parent kendo panelbar item

Utilizing a Kendo Angular UI panelbar within the sidepanel as a treemenu with submenu's, each item is linked to the Angular router routes array via routerLink. An issue arises when opening the submenu, where the parent menuitem's path is followe ...

Tsuquyomi pays no attention to any mistakes when opening

I have integrated Tsuquyomi as a Syntastic plugin for TypeScript error checking in Vim. However, I am facing an issue where only ESLint errors are displayed when I open a file, and Tsuquyomi errors are only visible when I save the file or manually run the ...

Is it possible to create a single directive that can handle both Structural and Attribute behaviors?

Trying to develop an Angular Directive that will handle various functionalities based on config input values Dynamically add elements to the DOM based on input values (similar to ngIf) Apply styling to rendered elements Add attribute properties such as d ...

Uncovering the mystery of retrieving form values from dynamic HTML in Angular 2

As a beginner in Angular 2, I am facing challenges extracting values from Dynamic HTML. My task involves having some Form Inputs and injecting Dynamic HTML within them that contain additional inputs. I followed the example by @Rene Hamburger to create the ...

After calling the service, Angular 2 is unable to perform any actions within the subscribe method

I am struggling with what to do after authenticating my user. Once I receive the data, I want to redirect them to the appropriate page based on their role and display their name on that page. I have tried various methods, but it seems like when I try to ca ...

Angular2's $compile directive functions similarly to AngularJS 1's $compile directive

I am currently in the process of migrating my project from Angular 1 to Angular 2 and I am in need of a compile directive. However, I am struggling to rewrite it to achieve the same functionality as before. app.directive("compile", compile); compile.$inje ...

What are some ways to customize the functionality of the data table filter in Angular Material?

Attempting to use the filter feature in Angular Material Data Table: When searching for "MATCHED", both "MATCHED" and "UNMATCHED" are displayed in the status column of the table. It seems this is due to the data object being reduced and concatenated befo ...

How do I determine in Angular (2+) when all child components have been initialized from the parent component?

Is there a lifecycle hook named "ngAfterAllChildrenInit" that can be used because ngAfterViewInit is called before the ngOninit of the children? I am currently trying to find a solution that avoids using setTimeOut or emitting events from all of the child ...

TypeScript and Redux mapDispatchToProps are not in sync

Below is my React component written in TypeScript: import React from 'react'; import {connect, ConnectedProps} from 'react-redux'; import logo from './assets/logo.png'; // import { Counter } from './features/counter/Count ...

What is the best way to extract data from an [object Object] and store it in an Array or access its values in Angular?

My Angular code is written in the component.ts file. I am fetching data from a backend API and using console.log to display the data. getInfo() { const params = []; params.push({code: 'Code', name: 'ty_PSD'}); params ...

Having trouble resolving all parameters for 'Router' in Angular 2 testing with Router

Currently, I am in the process of testing a component that has Router injected in the constructor (TypeScript): constructor( private _router: Router, private dispatcher: Observer<Action>, fb: FormBuilder ) { ... } Here are the test cases ...

Angular provides the capability to sort through data using various criteria

I have received an array of objects in a specific format from the server, which may contain more than 2 objects. [ {processId : 1, processName : "process1", country : "germany", companyCode:"IB" , companyHiringType:"FRE", masterClauses:[ {cl ...