【问题标题】:RXJs Angular - object undefinedRXJs Angular - 对象未定义
【发布时间】: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 模板添加

标签: angular rxjs


【解决方案1】:

修改模板代码为-

<div *ngIf = "lists.length>0">
    <h2>Test</h2>
    <div *ngFor="let item of lists"> {{ item }} </div>  
</div>

收集将通过模板显示的数据是组件的职责。您已经在getListTypes() 中通过调用服务方法来完成此操作,该方法使用服务返回的数据填充lists 数组。

模板的职责是显示组件收集的数据。使用*ngFor="let item of lists" 语句,您只需从组件中枚举已填充的lists 数组,并显示每个项目。您不应该从模板代码中调用服务。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-07
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    相关资源
    最近更新 更多