【问题标题】:How to display data from mvc controller using angular2如何使用angular2显示来自mvc控制器的数据
【发布时间】:2018-03-22 13:20:11
【问题描述】:

我已经为前端创建了一个包含 angular2 的项目,并且我还创建了 webapi 项目来使用数据库中的数据。 控制器代码返回模型:

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

我想在我的角度视图中迭代这个数据模型。我尝试创建有角度的 http 调用。但这在我的情况下是不可接受的。我需要从我的 mvc 控制器调用 webapi,然后从 angular2 视图中渲染该数据。

角度模型是:

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

}

Angular 服务代码是:

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');
}
 }

陷入困境,谷歌中可用的任何链接都无法正确解决我的问题。 请指导。 谢谢

【问题讨论】:

  • 我认为您需要调用完整的 URL,例如:localhost:PORT/Home/GetAllProducts
  • 你得到的错误是什么?此外,您应该使用新的 http api 而不是旧的:angular.io/guide/http
  • 我的 mvc 控制器方法中有正确的数据,我想绑定它并使用 angular2 循环,这是我在 angular2 中的新功能。
  • @krunalpatel "this._productUrl" 应该是实际的 'api 的托管路径' + 'api 的路由路径' 例如。 "localhost:50962/products/getdetails/1"

标签: asp.net-mvc angular


【解决方案1】:

您提到了_productUrl 作为您的 API 路径,但它应该是带有域名和操作调用的实际 API URL。

作为:

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

例如。

服务.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');
  }
}

您还可以为您的 API 设置环境变量并在您的所有服务中使用它。 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);

【讨论】:

    【解决方案2】:

    您可以使用ngForAsyncPipe

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

    【讨论】:

    • 假设您有一个使用您的服务的组件并且使用此模板,是的
    【解决方案3】:

    两者的组合(使用完整路径)Amol Bhor 和 Leon,而是将 uri vars 放入 env 文件使用 constants.ts 文件,因为对我来说环境与开发或生产环境有关。并且为了避免内存泄漏,使用异步管道,如果不使用取消订阅 onDestroy 方法。检查文档以获取详细信息。

    【讨论】:

    • 正确。对于来自“component.ts”的每个服务和数据调用,我们应该使用 Subscription 类使用 unsubscribe(),这是有意义的最佳实践。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多