角度-错误错误:尝试与'[object Object]'进行比较时出错。仅允许数组和可迭代

时间:2019-06-12 11:21:26

标签: angular laravel api

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

我做了log.console并收到此错误:

  

错误错误:尝试与'[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>

什么都没有加载。

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

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

TypeError: not all arguments converted during string formatting

并返回一个带有该对象的INSIDE对象的对象 像这样的东西:

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

您要显示的数据在该变量{ "sucess":"bla bla bla"; "data":[ ... ] <- Here }

在文件 smsmt.service.ts 中,方法'getSmsmts()'接收到一个dataSmsmts[])数组,但这不是您要发送的从后端。

后端发送一个对象(内部有一个数组),但是http.get()正在等待一个数组。这就是为什么它会引发错误。

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

this.http.get<Smsmt[]>

现在,在 smsmts.component.ts 文件中,尝试以下操作:

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', []))
    );
}

这可能有效。以前不能使用.pipe和.taps,但是应该可以使用。 请注意,这是一种解决方法,建议不要接收和返回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; }); } 。您可以创建带有两个属性的“ RequestResponse”之类的接口:成功 data ,这样一来,您就避免使用any类型