Accessing information from an Odata controller in Angular2

Greetings as a first-time question asker and long-time reader/lurker. I've been delving into learning angular2, but I'm facing some challenges when it comes to retrieving data from an odata controller. In my simple Angular 2 application, I'm attempting to load data returned from the odata controller into a list element in HTML.
Below is the interface for my Angular2:

interface Menu {
    id: number;
    name: string;
    route: string;
    decorator: string;
    description: string;
    OldTableId: string;
    TableName: string;
}

Here's my TypeScript/Angular 2 component file:

    import {
    ROUTER_DIRECTIVES,
    Http,
    Observable,
    MenuService,
    Component, OnInit
} from './index.ts';

@Component({
    selector: 'sidebar-menu',
    template: require('./sidebar-menu.html'),
    directives: [...ROUTER_DIRECTIVES],
    providers: [MenuService]
})
export class SidebarMenu {
    public menus: Menu[];
    public menu2s: Menu[];
    constructor(private _menuService: MenuService) {
    }
    ngOnInit() {
        this._menuService.getMenus()
            .subscribe((menus) => {
                this.menus = menus;
                console.log(val);
               },
            (err) => {
                console.log(err);
                }
            );
   }
}

In addition, here's my Angular2 service (MenuService) called during the initialization of the Angular 2 component:

import { Http, Response, Observable, Injectable} from './index.ts'

@Injectable()
export class MenuService {

    constructor(private _http: Http) { }

    getMenus() {
        //return this._http.get('/api/Menu/Menus') - api works fine
        return this._http.get('http://localhost:64157/odata/OldTables')
            .map((response: Response) => response.json())

            .catch(this._handleError);

    } _handleError(err: any) {
        //TODO - Give user a nice error message.
        console.log(err);
        return Observable.throw(err);
    };
    }

}

Now, let's move on to the HTML:

<ul class='nav navbar-sidebar'>
    <li>test</li>
    <li>
        <a [routerLink]="['/home']" class="router-link" [routerLinkActive]="['active']">
            <span class='glyphicon glyphicon-home'></span> Home
        </a>
    </li>
    <li *ngFor="let menu of menus" >
        <a [routerLink]="menu.name" class="router-link" [routerLinkActive]="['active']">
            <span class='glyphicon glyphicon-th-list {{menu.decorator}}'></span> {{menu.name}}
        </a>
    </li>
</ul>

The challenge arises when using an API controller that functions properly, but switching to an odata controller presents issues. While I can visualize the data in the browser through the log at console.log(val); within the component's initialization, I struggle to display it on the screen. My end goal is to utilize the data within the

<li *ngFor="let menu of menus" >
section of the HTML page. How can I render the data from the odata controller successfully? Most references I've come across pertain to web APIs.

Edit: Adding a glimpse of the data retrieved by my odata controller:

   {
      "odata.metadata":"http://localhost:64157/odata/$metadata#OldTables","value":[
        {
          "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e01222a0d21223b23203d0e212a2f3a2f60202f3827292f3a272120022720251b3c22">[email protected]</a>":"http://localhost:64157/odata/OldTables(15252)/OldColumns","OldTableId":15252,"TableName":"addbook"
        },{
          "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="77381b1334181b021a1904371813160316591916011e1016031e18193b1e191c22051b">[email protected]</a>":"http://localhost:64157/odata/OldTables(15253)/OldColumns","OldTableId":15253,"TableName":"adj01"
        },{
          "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d29dbeb691bdbea7bfbca192bdb6b3a6b3fcbcb3a4bbb5b3a6bbbdbc9ebbbcb987a0be">[email protected]</a>":"http://localhost:64157/odata/OldTables(15254)/OldColumns","OldTableId":15254,"TableName":"allcmy201"
        },{
          "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="024d6e66416d6e776f6c71426d666376632c6c63746b6563766b6d6c4e6b6c6957706e">[email protected]</a>":"http://localhost:64157/odata/OldTables(15255)/OldColumns","OldTableId":15255,"TableName":"allfut"
        }
      ]
    }

Answer №1

Everything is working now after I made sure to reference the "value" of the returned data. Here is the updated TS/Component code:

export class SidebarMenu {
    public menus: Menu[];

    constructor(private _menuService: MenuService) {
    }
    ngOnInit() {
        this._menuService.getMenus()
            .subscribe((menus) => {
                this.menus = menus.value;
                console.log(val.value[0]);
               },
            (err) => {
                console.log(err);
                }
            );
   }
}

I also made some modifications to my HTML code as shown below:

<ul>
    <li *ngFor="let menu of menus">
        <a [routerLink]="menu.OldTableId" class="router-link" [routerLinkActive]="['active']">
            <span class='glyphicon glyphicon-th-list {{menu.OldTableId}}'></span> {{menu.TableName}}
        </a>
    </li>
</ul>

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

service.js was identified as registered, however, it did not run as expected

I clicked on this link for my angular 2.0 tutorial journey. I managed to successfully display the list of drugs, but encountered an issue when I attempted to create the AuthorComponent. Unfortunately, my app stopped running due to the following error: Er ...

sending information to ng-content from mother in Angular

In the container-page.component.ts, I have set up the following structure using the ngrx approach. <parent-comp><child-comp [someInput]="someValue"></child-comp></parent-comp> Within the template of parent-comp, there is: <div ...

The TypeScript error is causing issues in the Express router file

Here is the structure of my module: import * as express from 'express'; let router = express.Router(); router.post('/foo', function(req,res,next){ // ... }); export = router; However, I'm encountering the following error: ...

Angular BehaviorSubject is failing to emit the next value

I am facing an issue with a service that uses a Behavior subject which is not triggering the next() function. Upon checking, I can see that the method is being called as the response is logged in the console. errorSubject = new BehaviorSubject<any> ...

Which return type is capable of handling null type values?

Currently, I am working on implementing conditional rendering in Typescript. However, I am facing an issue where using null as an alternative is resulting in the following error message: "Type 'Element | null' is not assignable to type &apo ...

How to retrieve start and end time values from dropdown options using formArray in Angular 8

Within my form group, I have start time and end time select options in a form array. My goal is to dynamically update the end time array based on the selected start time. <div [formGroupName]="skillIndex"> Start at: <select ...

Tips for sending a variable to control a particular panel within an accordion in Angular 2

I have a collection of ngbpanels that are dynamically created using ngFor. I need to expand or collapse a specific panel based on certain conditions, but the ID I provide for the panel is stored in a variable. The code does not recognize the panel ID when ...

Angular - Utilizing NgRx selector for efficient data update notifications

Is there a method to create a "data updated" indicator when I am not interested in the actual updated data itself? Consider a scenario with a reducer: const initialState: SomeReducer = { dataInQuestion: Array<SomeDto>, ... } Following an action ...

Unable to display custom component on app.component.html

After creating a unique custom component named core.component, I proceeded to import it into a module with the same name. core.component.html <div class="container-fluid text-left"> <div class="row rows-cols-2 top-bar"> ...

Using Angular-Meteor to make an HTTP request

I'm attempting to utilize the HTTP.call method with angular-meteor. Within my API backend folder, I am trying the following within a method: this.unblock(); try { const result = HTTP.call('GET', 'https://api.foursquare.com/v2/users/ ...

I am experiencing an issue where my code is not iterating over the data in my

The issue I'm facing with the code below is that it only displays the quantity of the first item, rather than all items in my shopping cart. import {ShoppingCartItem} from './shopping-cart-item'; export class ShoppingCart { constructor ...

"Upon compilation, the Angular app displays a blank screen instead of the expected

Recently, I attempted to create a client for a web application using Angular. I initiated the process with ng new client, and when I ran it at that point, it displayed the default webpage. Afterwards, I made modifications to the app.component.{html, css ...

What is the syntax for creating a zip function in TypeScript?

If I am looking to create a zip function: function zip(arrays){ // assume more than 1 array is given and all arrays // share the same length const len = arrays[0].length; const toReturn = new Array(len); for (let i = 0; i < len; i+ ...

Having trouble parsing the ICU expression. Utilizing angular for internationalization

I need to convert an array of left-menu items into another language, and I am encountering an error in my code. Here is the snippet: left-menu.component.html <ng-container *ngFor="let m of menuItems; let last = last"> <a mat-list-it ...

Lazy loading in Angular 14 delays the loading of a page until the content is clicked, ensuring a smoother user experience with reduced loading times

Greetings, I've been stuck on this issue for quite some time now. The problem I'm facing is that the page doesn't load until I click on the website. Can anyone please assist me with this? My expectation is that the default setting I have co ...

"Enhance user experience with Angular Material: Popup Windows that preserve functionality in the original window while staying vibrant and accessible

Exploring Angular Material Dialog and other Popup Window Components for a project. Making progress but facing some challenges. Here are the requirements: a) The original screen should not be grayed out, b) Users should be able to interact with the windo ...

Encountering issues when trying to build a Nestjs app with node-crc (rust cargo) in Docker

I am encountering an issue with building my Nest.js app using Docker due to a dependency called "node-crc" version "2.0.13" that fails during the docker build process. Here is my Dockerfile: FROM node:17.3.1-alpine RUN curl https://sh.rustup.rs -sSf | sh ...

Can you explain the meaning behind this TypeScript variable declaration syntax?

Can anyone explain the meaning of this code snippet: myCollection: Collection|any = null; I'm having trouble understanding it... Does it indicate that myCollection is set to type Collection, (which is an interface), with a default value of null? But ...

Can a custom CSS be linked directly to the angular-cli.json file?

I'm trying to incorporate custom CSS into my angular-cli.json file, but I haven't been able to find a successful method. I attempted to use the following code: "styles": [ "styles.css", "http://site.test/mycss.css" ], However, it does ...

Manipulating HTTP responses and variables in Angular 6

I created a custom application using the MEAN stack that allows users to sign up and log in. To enhance security, I want users to reconfirm their identity by entering their password or a PIN if they return to the application after some time. To achieve th ...