【问题标题】:Angular2 displaying http get response in componentAngular2在组件中显示http获取响应
【发布时间】: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' }];
   }*/
}
&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"&gt;&lt;/script&gt;

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);
   */
}
&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"&gt;&lt;/script&gt;

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


    【解决方案1】:

    您的属性以大写字母开头Id & Name

    您需要更新 Angular 代码以使用正确的属性。

    export class CategoryDTO {
        Id: string;
        Name: string;
    }
    
    <ul>
        <li *ngFor="let category of categoriesToDisplay">
            <span>{{category.Name}}</span>
        </li>
    </ul>
    

    【讨论】:

    • 太棒了,非常感谢。考虑到情况不同。不知道它是否区分大小写。
    【解决方案2】:

    等一下!我已经发现了我自己的一些问题,但这似乎并不完全是这样。正如 LLai 所说,很可能是因为您的属性的首字母大写!

    可能有点奇怪,但正在改变

    this.categoryService.getCategoriesFromApi()
      .subscribe((categoriesReturned) => this.categoriesToDisplay = categoriesReturned , err => console.log('err = ' + JSON.stringify(err, null, 2)));
    

    this.categoriesToDisplay = this.categoryService.getCategoriesFromApi()
      .subscribe((categoriesReturned) => this.categoriesToDisplay = categoriesReturned , err => console.log('err = ' + JSON.stringify(err, null, 2)));
    

    可能会成功。我遇到了同样的问题,解决方案只是将我想要更改的变量分配给 api 调用,另外更改订阅中的相同变量。我还应该澄清一下,在我的代码中,我没有为我的变量提供类型(即我的变量只是public variable,这并不理想,我仍在寻找解决方案。)希望这会有所帮助并祝你好运!

    (我还是相当新的 Angular,所以如果有人能解释为什么这会很可爱。谢谢!)

    【讨论】:

    • .subscribe() 返回Subscription。在这种情况下,我们希望 categoriesToDisplay 是一个数组,所以这不起作用。您可能正在考虑将 observable 存储在变量(没有 .subscribe)中,然后使用异步管道处理订阅的情况。所以 html 看起来像 *ngFor="let category of categoriesToDisplay | async"
    • 确实!这就是为什么我对我的代码有效的原因感到困惑。我也做了类似的 api 调用来从我的后端获取一个数组并将它分配给一个变量。但是我只在以下方面取得了成功:this.array = this.http.get(endpoint).subscribe(res =&gt; this.array = res) 非常奇怪!
    • 如果您将数组输入为array: any[],您将看到打字稿抛出错误Cannot assign type Subscription to type any[]。在这种情况下,应该不需要this.array =
    • 嗯,有道理!在我的代码中,我没有指定数组的类型;我只是有public array;
    • 啊哈! @LLai 感谢您与我讨论!我已经弄清楚为什么我会遇到问题:我们的大部分后端都存储在数组中......除了我一直遇到问题的一件事。这实际上是一个对象。将我的变量声明更改为public array: any = {} 是关键。干杯!
    猜你喜欢
    • 2017-07-31
    • 2017-02-16
    • 2021-03-06
    • 1970-01-01
    • 2016-07-16
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    相关资源
    最近更新 更多