我正在將JQuery用於HTTP請求到.NET控制器(我正在使用.NET MVC 4.5.2),但現在開始使用Angular 2,所以我想要處理這些相反,JQuery AJAX調用Angular 2。下面是我用之前的JQuery的,它的工作就像我想:將JQuery AJAX調用轉換爲Angular 2服務
$.get('/Plan/Variety/ListVarietiesInMenuForSelling')
.done(function(data){
console.log(data)
});
如何設置我的角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);
}
}
不幸的是,這是行不通的。相反,我得到這個錯誤在控制檯:
EXCEPTION: Uncaught (in promise): TypeError: Cannot read property '0' of undefined core.umd.js:3462
我已經能夠找到處理JSON數據,然後使用角度來分析數據,並將其格式化成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');
}
}
這裏是我怎麼綁定到HTML:
<div [innerHtml]="varietyListSelling"></div>
我用的,而不是{{varietyListSelling}}
因爲我需要要轉換爲HTML的字符串。
UPDATE
我升級打字稿和app.module.ts刪除我InMemoryWebApiModule和InMemoryDataService進口,這導致新的錯誤。錯誤現在說:EXCEPTION: Unexpected token < in JSON at position 4
這是因爲我們將我的HTML數據轉換爲JSON?我如何才能像我的JQuery一樣返回HTML?
你可以添加代碼,你調用getVarieties()函數? – Sefa
我編輯我的帖子,包括 – Brett