【发布时间】:2018-01-04 15:32:23
【问题描述】:
我正在构建我的第一个 angular2 应用程序,这是我的第一个服务调用。我正在使用服务堆栈 API。 GET 调用返回一个 IEnumerable 这个调用自己工作,当插入我的角度服务时,状态返回为 200,我可以在浏览器中看到返回的实际响应。但是,当此响应设置为在 component.html 中显示为 li 项时,它不会显示它们。相反,它只显示表示获得列表项的项目符号,但处理响应的方式存在一些问题。
Category.service.ts 代码如下:
import { Injectable } from '@angular/core';
import { CategoryDTO } from './Category';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class CategoryService {
constructor(private _http: Http) { }
getCategoriesFromApi(): Observable<CategoryDTO[]> {
return this._http.get("http://localhost:53426/category/find")
.map((response: Response) => <CategoryDTO[]> response.json());
}
/**
*
getCategoriesFromApi(): Category[] {
return [{ id: '123', name: 'Apparel' }];
}*/
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
category.component.ts 如下
import { Component, OnInit } from '@angular/core';
import { CategoryDTO } from './Category';
import { CategoryService } from './category.service';
import { DataserviceService } from '../dataservice.service';
@Component({
selector: 'show-category',
templateUrl: './category.component.html',
styleUrls: ['./category.component.css']
})
export class CategoryComponent implements OnInit {
categoriesToDisplay: CategoryDTO[];
constructor(private categoryService: CategoryService) { }
getCatsToDisplay(): void {
/**
* this.categoriesToDisplay = this.categoryService.getCategoriesFromApi();
*/
this.categoryService.getCategoriesFromApi()
.subscribe((categoriesReturned) => this.categoriesToDisplay = categoriesReturned , err => console.log('err = ' + JSON.stringify(err, null, 2)));
}
ngOnInit() {
this.getCatsToDisplay();
}
/**
* public values: Category[];
constructor(private _dataService: DataserviceService) { }
ngOnInit() {
this._dataService
.getAll<Category[]>()
.subscribe((data: Category[]) => this.values = data);
*/
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
category.component.html 如下
<ul>
<li *ngFor="let category of categoriesToDisplay">
<span>{{category.name}}</span>
</li>
</ul>
CategoryDTO 打字稿类(Category.ts)是这样的:
export class CategoryDTO {
id: string;
name: string;
}
最后,获取所有类别的 API 调用如下:
public IEnumerable<CategoryDTO> Get(FindCategory request)
{
var entities = this.Db.Select<Category>().OrderBy(c => c.Name);
return this.Mapper.Map<List<CategoryDTO>>(entities);
}
我看到的输出是这样的 output on the browser just shows that there is a list item but doesn't display the category
【问题讨论】:
标签: angular servicestack angular2-services angular2-components