【问题标题】:Angular - ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowedAngular - ERROR 错误:尝试区分“[object Object]”时出错。只允许使用数组和可迭代对象
【发布时间】:2019-10-26 21:31:43
【问题描述】:

我有一个 Angular7 前端和 Laravel 后端。我在 POSTMAN 上测试了端点,效果很好。但是,当我在 Serve 上进行测试时,它没有加载任何内容,并且出现此错误。

我做了 log.console 并得到了这个错误:

ERROR 错误:尝试比较“[object Object]”时出错。只允许使用数组和可迭代对象

error screenshot

postmanscrrenshot

ApiController:

public function indexSmsmt()
{
    $smsmts = Smsmt::all();
    return response()->json(['success' => true,'data'=>$smsmts], $this->successStatus);
}

public function showSmsmt($id)
{
    $smsmt = Smsmt::find($id);
    if (is_null($smsmt)) {
        return $this->sendError('SMS Incoming not found.');
    }

    return response()->json(['success' => true,'data'=>$smsmt], $this->successStatus);
}

public function storeSmsmt(Request $request)
{
    $smsmt = Smsmt::create($request->all());
    return response()->json(['success' => $smsmt], $this-> successStatus);
}

public function editSmsmt($id)
{
    $smsmt = Smsmt::find($id);
    return response()->json(['success' => true,'data'=>$smsmt], $this->successStatus);
}

public function updateSmsmt(Request $request, $id)
{
    $smsmt = Smsmt::find($id);
    $smsmt = $smsmt->update($request->all());
    return response()->json(['success' => true,'data'=>$smsmt], $this->successStatus);
}

public function deleteSmsmt($id)
{
    $smsmt = Smsmt::find($id)->delete();
    return response()->json(['success' => true], $this->successStatus);
}

environment.prod.ts

export const environment = {
    production: true,
    apiUrl:   'http://exampl.com/api',
};

smsmt.service.ts

import { Injectable } from '@angular/core';
import { Observable, of, throwError } from 'rxjs';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { catchError, tap, map } from 'rxjs/operators';
import { Smsmt } from '../models/smsmt';
import { environment } from 'src/environments/environment.prod';

const httpOptions = {
    headers: new HttpHeaders({'Content-Type': 'application/json'})
};

@Injectable({
    providedIn: 'root'
})

export class SmsmtService {
    private API_URL= environment.apiUrl;
    constructor(private http: HttpClient) { }

    getSmsmts (): Observable<Smsmt[]> {

        return this.http.get<Smsmt[]>(this.API_URL + '/indexSmsmt')
        .pipe(
            tap(smsmts => console.log('Fetch smsmts')),
            catchError(this.handleError('getSmsmts', []))
        );
    }

    getSmsmt(id: number): Observable<Smsmt> {

        const url = this.API_URL + '/editSmsmt' + '/{id}';

        return this.http.get<Smsmt>(url).pipe(
            tap(_ => console.log(`fetched smsmt id=${id}`)),
            catchError(this.handleError<Smsmt>(`getSmsmt id=${id}`))
        );
    }

    addSmsmt (smsmt): Observable<Smsmt> {
        return this.http.post<Smsmt>(this.API_URL + '/storeSmsmt', smsmt, 
            httpOptions).pipe(
                tap((smsmt: Smsmt) => console.log(`added smsmt w/ id=${smsmt.id}`)),
                catchError(this.handleError<Smsmt>('addSmsmt'))
            );
    }

    updateSmsmt (id, smsmt): Observable<any> {
        const url = this.API_URL + '/updateCSmsmt' + '/{id}';
        return this.http.put(url, smsmt, httpOptions).pipe(
            tap(_ => console.log(`updated smsmt id=${id}`)),
            catchError(this.handleError<any>('updateSmsmt'))
        );
    }

    deleteSmsmt (id): Observable<Smsmt> {
        const url = this.API_URL + '/deleteSmsmt' + '/{id}';

        return this.http.delete<Smsmt>(url, httpOptions).pipe(
            tap(_ => console.log(`deleted smsmt id=${id}`)),
            catchError(this.handleError<Smsmt>('deleteSmsmt'))
        );
     }

    private handleError<T> (operation = 'operation', result?: T) {
        return (error: any): Observable<T> => {

            // TODO: send the error to remote logging infrastructure
            console.error(error); // log to console instead

            // Let the app keep running by returning an empty result.
            return of(result as T);
        };
    }
}

smsmt.component.ts

import { Component, OnInit } from '@angular/core';
import { SmsmtService } from '../../../services/smsmt.service';
import { Router } from '@angular/router';
import { Smsmt } from '../../../models/smsmt';

@Component({
    selector: 'app-bulk-sms-outbox',
    templateUrl: './bulk-sms-outbox.component.html',
    styleUrls: ['./bulk-sms-outbox.component.scss']
})

export class BulkSmsOutboxComponent implements OnInit {
    displayedColumns: string[] = ['msisdn', 'message', 'telco','error_message','error_code', 'package_id'];
    data: Smsmt[] = [];
    isLoadingResults = true;    
    constructor(private api: SmsmtService) { }

    ngOnInit() {
        this.api.getSmsmts()
            .subscribe(res => {
                this.data = res;
                console.log(this.data);
                this.isLoadingResults = false;
            }, err => {
                console.log(err);
                this.isLoadingResults = false;
            });
    }

    ngOnDestroy(): void {
        document.body.className = '';
    } 
}

component.html

<tr  *ngFor="let datas of data| paginate: { itemsPerPage: 5, currentPage: p }; let i = index">
    <td>{{i + 1}}</td>
    <td>{{datas.msisdn}}</td>
    <td>{{datas.short_code_called}}</td>
    <td>{{datas.package_id}}</td>
    <td>{{datas.error_message}}</td>
    <td>{{datas.error_code}}</td>
</tr>

没有加载任何内容。

我该如何解决这个问题?

【问题讨论】:

  • 详细说明你真正需要什么,实际效果如何
  • 我想在component.html中显示数据。但是什么都没有出来

标签: angular laravel api


【解决方案1】:

在 Laravel 中获取数据时,您正在做的事情

return response()->json(['success' => true,'data'=>$smsmts], $this->successStatus);

并返回一个对象,该对象包含一个数组 INSIDE 比如:

{
   "sucess":"bla bla bla";
   "data":[ ... ] <- Here
}

你要显示的数据在那个变量data

在文件 smsmt.service.ts 中,方法 'getSmsmts()' 接收到一个数组 Smsmts[] (this.http.get&lt;Smsmt[]&gt;),但这不是您从后端发送的内容。

后端发送一个对象(里面有一个数组),但 http.get() 正在等待一个数组。这就是它抛出错误的原因。

你应该接收到 http.get() 方法接收一个对象,像这样:

getSmsmts (): Observable<any> { // Change here to any
    return this.http.get<any>(this.API_URL + '/indexSmsmt') // and here too
    .pipe(
        tap(smsmts => console.log('Fetch smsmts')),
        catchError(this.handleError('getSmsmts', []))
    );
}

现在,在 smsmts.component.ts 文件中,试试这个:

ngOnInit() {
    this.api.getSmsmts()
        .subscribe(res => {
            this.data = res.data; // change 'res' to 'res.data'
            console.log(this.data);
            this.isLoadingResults = false;
        }, err => {
            console.log(err);
            this.isLoadingResults = false;
        });
}

这可能有效。不习惯使用 .pipe 和 .taps,但它应该可以工作。 请注意,这是一种解决方法,不建议接收并返回any。您可以使用两个属性创建像“RequestResponse”这样的接口:sucessdata,这样就可以避免使用 any 类型

【讨论】:

  • 当我将“res”更改为“res.data”时,它下划线为红色,我收到另一个错误:任何属性“数据”在类型“Smsmt []”上不存在。ts(第2339章)
  • 尝试将 '.subscribe(res => { .... })' 更改为 .subscribe((res: any) => { ... })'。这将删除下划线,并可能解决问题
  • 将服务“getSmsmts()”的返回类型也更改为 Observable。问题是,该方法返回一个数组,但后端发送一个响应,其中包含数组。这就是错误的原因
  • 非常抱歉。请有点困惑。你能帮我在代码中更新你的答案吗
  • 是的,我可以,但请稍等,因为我正在打电话 xD 让我到达我的办公室,我会解释 :)
猜你喜欢
  • 2021-03-31
  • 2021-01-09
  • 2020-08-15
  • 2021-12-21
  • 2018-11-25
  • 2020-05-27
  • 2018-07-15
  • 2018-09-14
相关资源
最近更新 更多