角度服务 - GET返回undefined

时间:2018-01-10 18:15:52

标签: angular express service

我尝试使用角度服务从数据库中获取用户。在服务中执行GET请求时,我可以console.log(res)并获得响应。但是,当我尝试从另一个组件中获取数据时,它总是出现undefined。请帮忙。

users.service.ts

import { Injectable } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpClient, HttpClientModule } from '@angular/common/http';

@Injectable()
export class UsersService {

  constructor(
    private http: HttpClient,
    private route: ActivatedRoute
  ) { }

  users: any;

  getUsers() {
    this.http.get('http://localhost:3000/api/users').subscribe(res => {
      this.users = res;
      return this.users;
    });
  }

}

app.component.ts

import { UsersService } from './users.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers: [ UsersService ]
})

constructor(
    private http: HttpClient,
    private route: ActivatedRoute,
    private usersService: UsersService
  ) {
    this.users = usersService.getUsers();
  }

当我尝试在app.component.html中使用它时......

<div *ngFor="let user of users"></div>

用户未定义

4 个答案:

答案 0 :(得分:1)

如果您使用服务集中用户数据,请考虑以下事项:

import { Injectable } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpClient, HttpClientModule } from '@angular/common/http';

@Injectable()
export class UsersService {

  constructor(
    private http: HttpClient,
    private route: ActivatedRoute
  ) {
     this.getUsers()
          .subscribe(data => this.users = data);
  }

  users: any;

  getUsers() {
    return this.http.get('http://localhost:3000/api/users');

  }

}

然后在你的组件中:

constructor(
    private http: HttpClient,
    private route: ActivatedRoute,
    public usersService: UsersService <------ changed to public to make it available to the template
  ) {
     // this.users = usersService.getUsers(); <------ commented out, as users is now centralized in the service
  }

并在您的模板中:

<div *ngFor="let user of usersService.users"></div>

通过进行这些更改,您的getUsers()方法将仅在您的UsersService创建时调用(第一次出现在providers数组中),并且您的用户数据将可用于注入UsersService的任何组件。

答案 1 :(得分:0)

将您的服务更改为

 getUsers() {
    return this.http.get('http://localhost:3000/api/users')
      .map((response: Response) => response.json());
  }

并在组件中使用 subscribe()

   this.usersService.getUsers().subscribe((data) => {
      this.users = data;
    });

答案 2 :(得分:0)

您的代码存在的问题是您在订阅中返回。获取是异步调用Javascript不知道何时返回。

快速修复: 在进行REST调用之后直接获取prop。

在您的服务中:

this.http.get('http://localhost:3000/api/users').subscribe(res => {
      this.users = res;
    });
组件中的

usersService.getUsers();
this.users = usersService.users;

答案 3 :(得分:0)

您的服务类

import { Injectable } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpClient, HttpClientModule } from '@angular/common/http';

@Injectable()
export class UsersService {

constructor(private http: HttpClient, private route: ActivatedRoute) { }

getUsers(): Observable<any> {
    return this.http.get('http://localhost:3000/api/users')
    .map(res => res.json())
    .catch(this.handleError);
   }
}

private handleError(error: Response) {
    return Observable.throw(error || 'Server Error')
}

您的组件

import { UsersService } from './users.service';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
providers: [ UsersService ]
})

constructor(private http: HttpClient, private route: ActivatedRoute, private usersService: UsersService) {
    this.usersService.getUsers().subscribe(
        res => { this.users = res; },
        err => { console.log(err); }
    );
}

确保导入{ Observable }