Angular误差 - NGFOR仅支持绑定到迭代式的数组等绑定



我正在构建一个带有节点后端的角应用程序。这是我的server.js相关零件,带有休息端点:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cors = require('cors');
var mysql = require('mysql');
const con = mysql.createConnection({
    host: 'localhost',
    user: 'myusername',
    password: 'mypass',
    database: 'somedb'
});
con.connect((err) => {
    if (err) throw err;
    console.log('Connected!');
});
app.use(bodyParser.json());
app.use(cors());
app.route('/api/levels').get((req, res) => {
    con.query('SELECT * FROM level', (err, rows) => {
        if (err)
            res.send(JSON.stringify({ "status": 500, "error": err, "response": null }));
        else
            res.send(JSON.stringify({ "status": 200, "error": null, "response": rows }));
    });
});
...

这部分有效,我已经通过Postman进行了测试,我得到以下答复:

{
    "status": 200,
    "error": null,
    "response": [
        {
            "id": 1,
            "title": "A1.1"
        },
        {
            "id": 2,
            "title": "A1.2"
        },
        ... // the rest of the rows
    ]
}

角服务:

@Injectable()
export class LevelService {
  constructor(private http: HttpClient) {}
  public getAll() {
    return this.http.get('http://localhost:8000/api/levels/');
  }
  ...
}

该服务在组件中调用:

@Component({
  selector: 'app-level-list',
  templateUrl: './level-list.component.html',
  styleUrls: ['./level-list.component.css']
})
export class LevelListComponent implements OnInit {
  private levels: any[];
  constructor(private levelService: LevelService) { }
  ngOnInit() {
    this.levelService.getAll().subscribe((data: any[]) => this.levels = data);
  }
}

数据在组件的模板中使用:

<ul class="level-list">
  <li *ngFor="let level of levels">
    <app-level-list-item [level]="level">
    </app-level-list-item>
  </li>
</ul>

最后,它应该显示在主页上:

<div style="text-align:center">
  <h1>{{ title }}</h1>
</div>
<p>{{introText}}</p>
<app-level-list></app-level-list>

但是,当我打开页面时,没有可见数据,在控制台中有一个错误:

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'.
NgFor only supports binding to Iterables such as Arrays.

我在做什么错?

看起来您的服务响应不是数组类型,而是:

interface ServiceResponse {
    status: number;
    error: any; // not apparent of the type
    response: Level[];
}

我认为您需要更改getAll方法以映射它,以便响应是您的Level[]而不是ServiceResponse

public getAll(): Observable<Level[]> {
    return this.http.get<ServiceResponse>('http://localhost:8000/api/levels/')
        .map(res => res.response);
}

http请求返回您的响应类型,并且您发送的实际数据在其主体中。要获取它,请使用.json((方法,然后您可以像上面提到的属性一样访问您的数组。

this.levelService.getAll().subscribe(data => this.levels = data.json().response);

更新

出来的是,无需为httpclient使用.json((所以你可以写

this.levelService.getAll().subscribe(data => this.levels = data['response']);

,根据文档似乎需要支架符号。

我最近得到了这个例外。这归结为我试图在我认为是一系列物体的东西上努力的事实,但实际上不是。它是一个对象或一个原则。

我建议在浏览器中调试此问题,并验证levels实际上是一个数组。

您需要在服务中添加地图方法并将响应转换为JSON。将您的角服务更改为以下内容:

@Injectable()
export class LevelService {
  constructor(private http: HttpClient) {}
  public getAll() {
    return this.http.get('http://localhost:8000/api/levels/')
    .map(res=>res.json());
  }
  ...
}

相关内容

最新更新