How can Angular be taught to parse an object wrapped in JavaScript JSON format?

Having trouble accessing data from a JSON object called "Devices" returned from a web API using Angular 2 observables.

Here is the data structure shown in the console: https://i.sstatic.net/QrhjZ.png

When using a .json file without the 'Devices' wrapper, everything works fine...

If I fetch a .json file directly, it displays well

private _productUrl = 'api/devices/devices.json';

However, with this observable code, I am unsure how to incorporate the '.Devices'

private _productUrl = 'http://localhost:42822/api/device';

constructor(private _http: Http) { }

getProducts(): Observable<IDevice[]> {//Observable<IProduct[]> {
return this._http.get(this._productUrl)
    .map((response: Response) => <IDevice[]>response.json())
    .do(data => console.log("All: " + JSON.stringify(data)))
    .catch(this.handleError);
}

Answer №1

It seems like you are facing a CROS issue. To resolve this, add the following entry to the response header for api/device:

Access-Control-Allow-Origin: *

@Component({
    selector: 'json-com',
    template: `
        <h2><a [href]="titleUrl">{{title}}</a></h2>
        <div *ngFor="let d of devices">
            DeviceId:{{d.DeviceId}} DeviceStatus:{{d.DeviceStatus}}
        </div>`
})
export class JsonCom implements OnInit {
    title = 'stackoverflow.com/q/39113330/1810391';
    titleUrl = 'http://stackoverflow.com/q/39113330/1810391';

    private _productUrl = 'http://localhost:42822/api/device';

    devices: IDevice[] = [];

    constructor(private _http: Http) { }

    ngOnInit() {
    this.getProducts().subscribe(
            d => {
                console.log('getProducts():' + JSON.stringify(d));
                this.devices = d.Devices;
            },
            e => console.log('error: ' + JSON.stringify(e)));
    }

    getProducts() {
    return this._http.get(this._productUrl)
            .do(d => console.log('_http.get():' + JSON.stringify(d)))
            .map(r => r.json())
    }
}

If the above solution doesn't work, kindly provide me with the console log for further assistance.

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

"Utilizing MongoDB to update a collection document with a JSON object imported by a client within the Meteor

I have a JSON object that the client is importing (imported as XLSX and converted to JSON). Each JSON object contains a reference and several other fields that are inserted into my collection. My goal is to update a document in my collection whenever a c ...

Using a package manager with Deno: Best practices and tips

I just learned about Deno, the alternative to NodeJS. I'm trying to figure out how to use yarn or npm with Deno, but I can't seem to find any instructions. Is there a way to use yarn or npm with Deno? ...

Utilizing mapped types in a proxy solution

As I was going through the TS Handbook, I stumbled upon mapped types where there's a code snippet demonstrating how to wrap an object property into a proxy. type Proxy<T> = { get(): T; set(value: T): void; } type Proxify<T> = { ...

Can a specific type be created for a nested object that has varying levels of depth?

One of my functions organizes objects based on the length of an input array. For example: fn(['a']) -> Record<string, string> fn(['a', 'b']) -> Record<Record<string, string>> I've defined the ret ...

Infinite cycle occurs in Angular2 when adding a component

I am currently working with rows and an array containing column specifications. My approach involves looping through the rows and columns to add content within TD elements, which has been successful thus far. However, I encounter browser crashes when attem ...

Progression from Angular2-rc1 to Angular2-rc2 encounters TypeScript error: anticipating ',' (TS1005)

Encountering an issue with upgrading Angular2 from RC1 to RC2, following exception is being thrown: https://i.sstatic.net/bB6di.png Here's my main.ts file, I haven't made any changes to it during the upgrade process. Line 13 is where the bootstr ...

Enhancing asynchronous operations with TypeScript and ExpressJs using Async/Await

Exploring the benefits of TypeScript's async/await in an Express project, I came across the following code snippet that seems to be stuck indefinitely without producing any outcome. Any thoughts on how to fix this issue? .. router.get('/test ...

Can anyone provide guidance on incorporating jQuery typing into an angular2 seed project?

I'm struggling to incorporate jQuery typings into my Angular2-seed project. Within my component, I am utilizing jQuery in the following manner: declare let $: any; export class LeafletComponent implements OnInit { ngOnInit(): void { th ...

Tips for showing various tooltip text when iterating through a list?

I am currently working on a project where I am looping through a list and attempting to assign different tooltip text to various icons. However, I am struggling with the implementation. Here is a snippet of my code: <React.Fragment key={sv.key ...

Struggling to make the transition from JavaScript to TypeScript in Ionic 2

I recently updated the file extensions for my application files, including app/app.js. Error: Cannot find module 'app/app.js' from 'app_folder' The error message doesn't specify which file I need to locate to resolve the issue. ...

Accessing a particular level within a JSON object in Node.js

I'm dealing with a two level JSON structure {"Policy": { "Channel": "online", "Credit Score": "20000", "Car": [{ "Age": "28", ...

Is a CSV Import a Better Fit for My Data Compared to a JSON Import?

Currently, I'm challenging myself to utilize mongoDB under the guise of its supposed "convenience" in handling JSON data. However, as expected, things are never as straightforward as they seem. For this particular scenario, I am contemplating reverti ...

Building with React js allows developers to generate downloadable files from JSON data received from an API response

I need assistance with my React.js application, which is fetching a JSON object from an API. How can I convert this JSON object into a CSV file and provide a download link for users using React.js? { "data": [ { "loca ...

Creating a new column in an SQL query by converting a set of results from another table into an array

Currently, I am facing a challenge in creating a join query that involves two tables and requires including a new column that is essentially the result of a separate query from another table. The catch here is that this new column needs to be stored as an ...

I possess a JSON object retrieved from Drafter, and my sole interest lies in extracting the schema from it

Working with node to utilize drafter for generating a json schema for an application brings about too much unnecessary output from drafter. The generated json is extensive, but I only require a small portion of it. Here is the full output: { "element": ...

Can the output type of a function be dynamically determined by using the function parameter name as the property in an interface?

I am attempting to dynamically assign the output of a function based on the name of the input parameter within an existing interface: interface MyInterface { typeA: string; typeB: boolean; typeC: string; typeD: number; ... } const myFunction: ( ...

Issues with displaying results from a local JSON file using Angular 4 services seem to be

I have developed a User.service.ts service where I have implemented the following code: getContactDetials(){ return this.http.get(this.config.apiUrl + 'assets/data/contact-details.json') .map(response => response.json()); ...

What could be the reason behind the malfunction of nativescript-phone on Android during plugin build?

I am encountering a particular build error while trying to deploy our NativeScript app on my Android Studio Emulator: > Failed to build plugin nativescript-phone : Error: spawn ./gradlew ENOENT Exception in thread "DisconnectableInputStream source ...

Convert JSON properties using NewtonSoft JsonConverter to rename a property to the value of another property

In my project, I have created a custom class called ValueInteger: public class ValueInteger { [JsonIgnore] public string ValueName { get; set; } public int Value { get; set; } [JsonProperty("timestamp")] public UInt64 TimeStamp { get ...

Discovering the worth of a variable outside of a subscription or Promise within Ionic 3

Apologies for my English. I am encountering an issue when attempting to view the results of a REST API using both subscribe and Promise methods. Within my provider, I have the following code: Provider: import { HttpClient } from '@angular/common/h ...