this.data.getUsers(...)。subscribe不是函数

时间:2019-04-13 17:38:06

标签: node.js angular angular7

从API提取详细信息并尝试在打印用户列表时列出相同的获取错误,可以使用相同的代码进行打印。

以下是我的home.component.ts

constructor(private formBuilder: FormBuilder, private data: DataService) { }
ngOnInit() {
this.data.getUsers().subscribe(data => {
        this.users = data
        console.log(this.users);
      }
    );
}

以下是我的数据服务代码

getUsers() {

    return this.http.get('https://reqres.in/api/users');
  }

以下是我正在尝试的html循环

<ul *ngIf="users">
  <li *ngFor="let user of users.data">
    <img [src]="user.avatar">
    <p>{{ user.first_name }} {{ user.last_name }}</p>
  </li>
</ul>

2 个答案:

答案 0 :(得分:1)

通过您的代码Working Stackblitz

重新检查

component.ts

import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'my-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  users;
  constructor(private data: DataService){}
  ngOnInit() {
    this.data.getUsers().subscribe(data => {
      this.users = data ;
    })
  }
}

service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class DataService {

  constructor(private http: HttpClient) { }
  getUsers() {
    return this.http.get('https://reqres.in/api/users');
  }

}

component.html

<ul *ngIf="users">
  <li *ngFor="let user of users.data">
    <img [src]="user.avatar">
    <p>{{ user.first_name }} {{ user.last_name }}</p>
  </li>
</ul>

答案 1 :(得分:0)

有效...我清除了npm的缓存,它有效..