Miguel Teixeira
Miguel Teixeira

Reputation: 793

Angular2: Http.get<Object[]> map undefined

I have a service defined with these imports:

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/map";
import { Subject } from "rxjs/Subject";
import { Navigation } from "../Shared/app.home";
import { Module } from "../Shared/app.home";

Then in the service I define a method:

getNavigationModules(): Observable<Navigation[]> {
    return this.http.get<Module[]>("/api/modules/getuserpreferences").map((mods) => {
        return mods.map(m => {
            var nav = new Navigation();
            nav.id = m.Id;
            nav.name = m.Name;
            nav.isFavorite = m.IsFavorite;
            nav.url = m.FriendlyUrl;
            nav.status = (m.ModuleProperties["Status"] != null && m.ModuleProperties["Status"] === "Online") ? "on" : "off" ;
            nav.type = m.Type;

            return nav;
        });
    });
}

When the method is called, I get the error that map is undefined. When calling mods.map I assume that by calling http.get that mods will be an Module array, but when I use the debugger (Chrome) I see that the debugger treats mods as an Object with a property Modules, this one being the Module array.

enter image description here

But if I change the code to mods.Modules.map I get an error when compiling because mods is in fact an Module[] and not an object.

What am I missing?

Thanks

Upvotes: 0

Views: 503

Answers (1)

JB Nizet
JB Nizet

Reputation: 691745

You're telling TypeScript that what the backend will send back is an array of Module. But it's not. It's an object, with one field named Modules, which is an array of Module. So tell the correct thing to TypeScript:

getNavigationModules(): Observable<Navigation[]> {
    return this.http.get<{Modules: Module[];}>("/api/modules/getuserpreferences").map((mods) => {
        return mods.Modules.map(m => {
            var nav = new Navigation();
            nav.id = m.Id;
            nav.name = m.Name;
            nav.isFavorite = m.IsFavorite;
            nav.url = m.FriendlyUrl;
            nav.status = (m.ModuleProperties["Status"] != null && m.ModuleProperties["Status"] === "Online") ? "on" : "off" ;
            nav.type = m.Type;

            return nav;
        });
    });
}

Upvotes: 2

Related Questions