0

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

4
  • I think that you need to call the complete URL like: localhost:PORT/Home/GetAllProducts Commented Mar 22, 2018 at 13:25
  • What is the error you get? Also, you should use the new http api instead of the old one: angular.io/guide/http Commented Mar 22, 2018 at 13:27
  • i am having correct data in my mvc controller method, i want to bind that and loop over using angular2, the this is i am new in angular2. Commented Mar 22, 2018 at 13:30
  • @krunalpatel "this._productUrl" should be actual 'hosted path of api' + 'route path of api' for example. "localhost:50962/products/getdetails/1" Commented Mar 22, 2018 at 13:58

3 Answers 3

0

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);
Sign up to request clarification or add additional context in comments.

Comments

0

You can use ngFor and the AsyncPipe

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

1 Comment

asuming that you have a component that uses your service and with this template, yes
0

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.

1 Comment

Correct. It make sense and best practice that for every service and data call's from 'component.ts' we should use unsubscribe() using Subscription class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.