如何在Angular 2中检索数据?

问题描述 投票:0回答:2

我正在使用post方法。

这是我的ts文件:

viewt(testid)
{
    $('#myModal22').modal('show');
    var param2 = {
        testid:testid,
    }
    this.service.get_tquestion(param2).subscribe(data => {
        this.test_question1 = data;
        console.log(data);
        console.log(this.test_question1);
    });
}

HTML代码:

<ng-container *ngFor="let v of test_question1">
    <tr >
        <td>{{v.questionid}}</td>
        <td>{{v.questionname}}</td>
    </tr>
</ng-container>

和服务部分:

get_tquestion(param) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    // this.createAuthorizationHeader(headers);
    return this.http.post(
        this.base_url + "test/getquestion", param, {headers: headers })
        .map((res: Response) => res.json());
}

API响应如下:

找不到'对象'类型的不同支持对象'[object Object]'。 NgFor仅支持绑定到诸如Arrays之类的Iterables。

回应我得到的是:

{“代码”:200,“结果”:[{“questionid”:1034,“questionname”:“在下面的句子中标识形容词。我们在午餐时带了几个三明治。(硬)”,“持续时间”:60 }]}

但我不能用HTML显示。

angular
2个回答
3
投票

您将API的整个响应传递给test_question1变量。由于响应是一个对象而且它不是Iterable,所以你不能将它与ngFor指令一起使用。要解决此问题,您可以从服务返回数据数组:

return this.http.post(this.base_url + "test/getquestion", param, { headers: headers })
    .map((res: Response) => res.json().Results);}

或者在订阅中分配响应对象的属性:

this.test_question1 = data.Results;

0
投票

你应该试试这个,对我有用:

在你的service.ts

import { Injectable } from '@angular/core';
import { URLSearchParams, Http, HttpModule, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';


@Injectable()
export class AuthService {
constructor(private http: Http) { }

authenticate(user_creds)
{
  //console.log(user_creds);
  const header = new Headers();
  header.append('Content-Type', 'application/x-www-form-urlencoded');
  return this.http.post('http://localhost/valuesassessment/api/login/authenticate_login', user_creds, { headers: header })
    .map((res: Response) => res.json());
}
}

在你的.ts

import { AuthService } from '../auth.service';

export class LoginComponent implements OnInit {
    session_data: any = {};
constructor( private authService: AuthService ) 
{ 
  // your logic before init
}

authenticate(x)
{
    this.authService.authenticate(x)
                    .subscribe(data => 
                    {
                      if(data.ResponseCode == 411)
                      {
                        // console.log(data.ResponseCode)
                        this.session_data = data;
                      }
                      else
                      {
                        this.session_data = data;
                        // console.log(this.session_data);
                      }
                    })
    this.session.store('header',this.header);
}

请注意,在为qazxsw poi分配响应之前,我们已将其初始化为类型qazxsw poi。

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.