krunal patel
krunal patel

Reputation: 41

How to display data from mvc controller using angular2

I have created a project including angular2 for front-end and i also created webapi project to consume data from database. Controller Code return model:

UserInfo = JsonConvert.DeserializeObject<List<UsersVM>>(Response);

I want to iterate over this data model in my angular view. i trid creating angular http calls. but this not acceptable in my case. i need to call webapi from my mvc controllers and just to render that data from angular2 views.

Angular Model is :

export interface IUser {
Id: number;
ProductName: string;
ProductPrice: string;

}

Angular Service Code is:

import {
Injectable
} from '@angular/core';
import {
Http, Response, RequestOptions,
Request, RequestMethod, Headers
} from '@angular/http';
import {
   IUser
} from './user';

import {
Observable
} from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
@Injectable()
export class UserService {
private _productUrl = 'Home/GetAllProducts';  
constructor(private _http: Http) { }   
getProducts(): Observable<IUser[]> {        
    return this._http.get(this._productUrl)
        .map((response: Response) => <IUser[]>response.json().value)
        .catch(this.handleError);
}

private handleError(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
}
 }

Stuck in this, any links available in google doesn't correctly solve my issue. Please guide. Thanks

Upvotes: 0

Views: 660

Answers (3)

Geovanny Q. Perez
Geovanny Q. Perez

Reputation: 24

A combination from both (use full path) Amol Bhor & Leon, and instead has the uri vars into env file use constants.ts file because for me environment is related to dev or prod environments. And to avoid memory leaks use asyn pipe, if not use unsubscribe into onDestroy method. Check docs for detail info.

Upvotes: 0

Amol Bhor
Amol Bhor

Reputation: 2542

You have mentioned _productUrl as your API path, but it should be actual API URL with domain name and action call.

as :

private _productUrl = 'localhost:50962/products/';

Eg.

Service.ts

import { Injectable } from '@angular/core';
import { Http, Response, RequestOptions,Request, RequestMethod, Headers } from '@angular/http';
import { IUser } from './user';    
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()
export class UserService {

  private _productUrl = 'localhost:50962/products/';

  constructor(private _http: Http) { }   

  getProducts(): Observable<IUser[]> {   

    let header = this.initHeaders();
    let options = new RequestOptions({ headers: header, method: 'get' });

    return this._http.get(this._productUrl + 'getAllProducts', options)
        .map((response: Response) => <IUser[]>response.json().value)
        .catch(this.handleError);
  }

  private initHeaders(): Headers {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Access-Control-Allow-Origin', '*');
    return headers;
  }

  private handleError(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
  }
}

Also you can set environment variable for your API and use it in all your services. environment.API

export const environment = {
  API: 'http://localhost:50962/',
  WordPressAPI: 'http://localhost:58451/',
  FacebookClientId: '45******',
}


return this._http.get(environment.API + 'products/getAllProducts', options)
        .map((response: Response) => <IUser[]>response.json().value)
        .catch(this.handleError);

Upvotes: 0

Leon
Leon

Reputation: 480

You can use ngFor and the AsyncPipe

<div *ngFor="let user of getProducts() | async">
    {{user.Id}}
    {{user.ProductName}}
    {{user.ProductPrice}}
</div>

Upvotes: 0

Related Questions