Angular 5处理来自POST请求

时间:2018-02-20 16:01:33

标签: angular typescript

我正在尝试将应用程序从Angular 1.x转换为Angular 5.应用程序向服务器发出POST请求,以字符串,字符串和数组的形式响应结果。根据2个字符串的值,我需要在* ngFor循环中使用数组来显示结果。这在Angular 1中很容易实现,使用工厂发出请求,然后使用then子句来分解响应的各个部分。

pageFactory.getDetails(getUrl, myDrawing)
    .then(
        function(response) {
            $scope.drawing = response.data.drawing;
            $scope.message = response.data.message;
            $scope.error = response.data.error;
            if ($scope.error != '') {
                    $scope.hide = false;
            }
            $scope.hide2 = false;
    });

我无法使用Angular 5找到与此类似的方法。我可以使用Observable和subscribe子句在服务中发出请求来执行它。我不能做的是打破2个字符串和数组。

我的服务是:

import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {catchError, map, tap} from 'rxjs/operators';

import {User} from './user';
import {Observable} from 'rxjs/Observable';
import {of} from 'rxjs/observable/of';

const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'})
};
const usersUrl = 'http://aqp.rvw/processUsers.php';
const formData: FormData = new FormData();
formData.append('type', 'getAll');


@Injectable()
export class UserService {
  users: User[];
  constructor(
    private http: HttpClient) {}
  getUsers(): Observable<object> {
    return this.http.post(usersUrl, formData)
      .pipe(
      catchError(this.handleError('getUsers', []))
      );
  }

和主要主要成分

import {Component, OnInit} from '@angular/core';
import {User} from '../user';

import {UserService} from '../user.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
  users: User[];
  response: object;
  constructor(private userService: UserService) {}

  ngOnInit() {
    this.getUsers();
  }

  getUsers(): void {
    this.userService.getUsers()
      .subscribe(response => this.response = {message: response['message'], error: response['error'], users: response['users']});
  }
}

我的模板是:

<h2>List of users</h2>
{{message}}
<ul class="users">
    <li *ngFor="let user of users">{{user.user}}</li>
</ul>

我的代码显示没有错误,但我没有在HTML中看到列表,只是标题。为了让这项工作正常,我需要做些什么改变?

1 个答案:

答案 0 :(得分:0)

我或多或少地解决了这个问题。我的服务现在看起来像这样

import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {catchError, map, tap} from 'rxjs/operators';

import {MyClass} from './myclass';
import {Observable} from 'rxjs/Observable';
import {of} from 'rxjs/observable/of';

const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'})
};
const usersUrl = 'http://aqp.rvw/processUsers.php';
const formData: FormData = new FormData();
formData.append('type', 'getAll');


@Injectable()
export class UserService {
  answers: MyClass;
  message: string;
  error: string;
  constructor(
    private http: HttpClient) {}
  getUsers(): Observable<MyClass[]> {
    return this.http.post<MyClass[]>(usersUrl, formData)
      .pipe(
      catchError(this.handleError('getUsers', []))
      );
  }
}

我的组件现在是

import {Component, OnInit} from '@angular/core';
import {User} from '../user';
import {MyClass} from '../myclass';

import {UserService} from '../user.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
  answers: MyClass[];
  users: User[];
  constructor(private userService: UserService) {}

  ngOnInit() {
    this.getUsers();
  }

  getUsers(): void {
    this.userService.getUsers()
      .subscribe(data => {
        this.answers = data;
      });
  }
}

我有一个新班级

import {User} from './user';
export class MyClass {
  message: string;
  error: string;
  users: User; /*{user: string, role: string; project: string};*/
}

我的模板现在看起来像这样

<h2>List of users</h2>
<div class='container'>
    <div class='row'>
        <div class='col-sm-4'>Name</div>
        <div class='col-sm-4'>Role</div>
        <div class='col-sm-4'>Project</div>
    </div>
    <div class='row' *ngFor="let user of answers?.users">
        <div class='col-sm-4'>{{user.user}}</div>
        <div class='col-sm-4'>{{user.role}}</div>
        <div class='col-sm-4'>{{user.project}}</div>
    </div>
</div>

<div>{{answers?.message}} and {{answers?.error}}.</div>

这适用于Windows 10上的Firefox和Chrome,但在Microsoft Edge上无效。任何想法为什么这应该是?