将 JQuery AJAX 调用转换为 Angular 2 服务

Bre*_*ett 5 asp.net-mvc angular2-services angular

我使用 JQuery 来处理对 .NET 控制器的 http 请求(我使用的是 .NET MVC 4.5.2),但现在我开始使用 Angular 2,所以我想用 Angular 2 处理那些 JQuery AJAX 调用。这是我之前使用的 JQuery,它的工作方式和我想要的一样:

$.get('/Plan/Variety/ListVarietiesInMenuForSelling')
    .done(function(data){
        console.log(data)
    });
Run Code Online (Sandbox Code Playgroud)

我如何设置我的 Angular 2 服务来完成同样的事情?我试过下面的代码:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';  

@Injectable()
export class SellingMenuVarietiesService {
    private url = '/Plan/Variety/ListVarietiesInMenuForSelling';  // URL to web api    

    constructor(private http: Http) { }

    getVarieties() {
        return this.http.get(this.url);
    }       
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不起作用。相反,我在控制台中收到此错误:

EXCEPTION: Uncaught (in promise): TypeError: Cannot read property '0' of undefined        core.umd.js:3462
Run Code Online (Sandbox Code Playgroud)

我能够找到处理 JSON 数据然后使用 Angular 解析数据并将其格式化为 HTML 的唯一示例。我的控制器已经返回了我需要的 HTML,所以我不需要 Angular 来解析 JSON。我如何让 http 请求像使用 JQuery 时一样工作?

为了清楚起见,出于测试目的,我更改return this.http.get(this.url);return '<h1>test data</h1>';并能够正确显示它,所以我知道唯一的问题是 http 请求。

编辑:这是我调用的代码getVarieties()

export class SellingMenuVarietiesComponent implements OnInit {   
    varietyListSelling: any;    

    constructor(
        private router: Router,
        private sellingMenuVarietiesService: SellingMenuVarietiesService) { }    

    ngOnInit(): void {        
        this.varietyListSelling = this.sellingMenuVarietiesService.getVarieties();
        console.log('initializing SellingMenuVarietiesComponent');
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我将它绑定到 HTML 的方式:

<div [innerHtml]="varietyListSelling"></div>
Run Code Online (Sandbox Code Playgroud)

我使用它而不是{{varietyListSelling}}因为我需要将字符串转换为 HTML。

更新

我升级了 TypeScript 并从 app.module.ts 中删除了我的 InMemoryWebApiModule 和 InMemoryDataService 导入,这导致了一个新错误。错误现在说:EXCEPTION: Unexpected token < in JSON at position 4

这是因为我们正在将我的 HTML 数据转换为 JSON 吗?我怎样才能像我的 JQuery 那样返回 HTML?

Edu*_*nis 1

你可以这样做:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class SellingMenuVarietiesService {
    private url = '/Plan/Variety/ListVarietiesInMenuForSelling';  // URL to web api    

    constructor(private http: Http) { }

    public getVarieties(): Observable<any> {
        return this.http.get(this.url).map(response=>{return response});
    }       
}
Run Code Online (Sandbox Code Playgroud)

然后使用该服务:

 this.sellingMenuVarietiesService.getVarieties().subscribe(res => {
    console.log(res);
    });
Run Code Online (Sandbox Code Playgroud)

更新:

您尝试渲染的 html 未渲染,因为渲染模板时请求尚未完成。一个可能的解决方案是向 div 标签添加 ngIf。

div *ngIf="varietyListSelling" [innerHtml]="varietyListSelling"></div>
Run Code Online (Sandbox Code Playgroud)