【发布时间】:2021-03-21 12:00:19
【问题描述】:
我将以我对 Angular 非常陌生的知识作为开头,因为我正在努力让简单的事情发挥作用并且非常努力!
我有一个简单的 WebAPI,它将返回一个包含三个对象的 JSON 数组:
网址:https://localhost:44397/api/account
testListType.ts
export interface listTypes {
limitTypeId: number;
limitTypeText: string;
limitTypeActive: boolean;
}
然后我将 rxjs 加载到服务中
test.service.ts
import { Injectable } from '@angular/core';
import { listTypes } from '../models/testListType';
import { Observable, of } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class TestService {
getlistTypes(): Observable<listTypes[]> {
var returnable = this.http.get<listTypes[]>('https://localhost:44397/api/account');
return returnable;
}
constructor(private http: HttpClient) { }
}
最后尝试在组件上显示该返回的内容
testing.component.ts
import { Component, OnInit } from '@angular/core';
import { listTypes } from '../models/testListType';
import { TestService } from '../services/test.service';
@Component({
selector: 'app-testing',
templateUrl: './testing.component.html',
styleUrls: ['./testing.component.css']
})
export class TestingComponent implements OnInit {
lists: listTypes[] = [];
constructor(private testService: TestService) { }
ngOnInit(): void {
this.getListTypes();
}
getListTypes(): void {
this.testService.getlistTypes()
.subscribe(lists => this.lists = lists);
}
}
这是修改 Angular 上的英雄时代教程以满足我的要求的结果。不幸的是,它什么也没显示,而且我太新手了,无法理解如何调试 subscribe 方法(我已经尝试并获得了一个无意义的对象)。
当我尝试访问列表时,我可以在调试器中看到以下内容:
未捕获的引用错误:未定义列表
毫无疑问,我错过了一个基本原理,我希望 Angular 专家会在几秒钟内看到它,但我已经盯着这个看了 2 个小时了!
任何帮助都会很棒。
更新 - 添加组件 html
testing.component.html
<div *ngIf="testService.listTypes.length">
<h2>Test</h2>
<div *ngFor='let lists of testService.listTypes'> {{listTypes}} </div>
</div>
【问题讨论】:
-
分享您使用组件中的
lists的模板代码(html)。 -
@atiyar 模板添加