简体   繁体   English

Angular 4-映射HTTP JSON响应

[英]Angular 4 - Mapping HTTP JSON Response

I am trying to setup a mean stack crud application. 我正在尝试设置一个普通的堆栈程序。 The routes and the functionality is setup and tested using postman. 使用邮递员设置和测试路线和功能。 I am getting correct responses for all the routes. 我对所有路线都得到了正确的答复。 Now I am trying to add the view part where the routes are called internally by the Angular application. 现在,我试图添加视图部分,Angular应用程序在内部调用路由。 I am trying to setup a basic get route. 我正在尝试设置基本的获取路线。 Following is my component code: 以下是我的组件代码:

import { Component, OnInit } from '@angular/core';
import { UserService } from '../user.service';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
  users: {};
  constructor(private userService: UserService) { }
  ngOnInit() {
    this.getUsers();
  }
  getUsers() {
    this.userService.getAllUsers().subscribe(data => this.users = data);
  }
}

and the service contains the following code: 并且该服务包含以下代码:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';    
@Injectable()
export class UserService {    
  constructor(private http: Http) { }    
  getAllUsers() {
    this.http.get('/api/users')
      .map(res => res.json());
  }    
}

A sample response of the route using postman is as follows: 使用邮递员的路线示例响应如下:

{
    "status": true,
    "err": null,
    "data": [
        {
            "_id": "59d5db344c46e83a14b94616",
            "name": "test"
        },
        {
            "_id": "59d5db3c4c46e83a14b94617",
            "name": "hello"
        }
    ]
}

It always telling me the following error: Property 'subscribe' does not exist on type 'void'. 它总是告诉我以下错误: Property 'subscribe' does not exist on type 'void'.

What am I doing wrong? 我究竟做错了什么? Can someone point me the standard way to do this? 有人可以指出我执行此操作的标准方法吗?

Try this : 尝试这个 :

You forgot to return in your getAllUsers() 您忘记了返回getAllUsers()

getAllUsers() {
   return this.http.get('/api/users')
      .map(res => res.json());
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM