Angular 角度误差误差:尝试区分';[对象对象]';。只允许使用数组和iterables

Angular 角度误差误差:尝试区分';[对象对象]';。只允许使用数组和iterables,angular,laravel,api,Angular,Laravel,Api,我有一个Angular7前端和Laravel后端。我在POSTMAN上测试了端点,效果非常好。然而当我测试发球时,它没有加载任何内容,我得到了这个错误 我没有登录到log.console,因此出现以下错误: 错误:尝试区分“[object]”时出错。只允许使用数组和iterables ApiController: public function indexSmsmt() { $smsmts = Smsmt::all(); return response()->json(

我有一个Angular7前端和Laravel后端。我在POSTMAN上测试了端点,效果非常好。然而当我测试发球时,它没有加载任何内容,我得到了这个错误

我没有登录到log.console,因此出现以下错误:

错误:尝试区分“[object]”时出错。只允许使用数组和iterables

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);
}
环境.产品ts

export const environment = {
    production: true,
    apiUrl:   'http://exampl.com/api',
};
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);
        };
    }
}
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 = '';
    } 
}
SMT.service.ts

export const environment = {
    production: true,
    apiUrl:   'http://exampl.com/api',
};
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);
        };
    }
}
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>

{{i+1}}
{{datas.msisdn}
{{datas.short_code_called}
{{datas.package_id}
{{datas.error_message}
{{datas.error_code}
没有加载任何内容


如何解决此问题?

在Laravel中获取数据时

return response()->json(['success' => true,'data'=>$smsmts], $this->successStatus);
并返回一个对象,其中包含一个数组 比如:

{
   "sucess":"bla bla bla";
   "data":[ ... ] <- Here
}
现在,在smts.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;
        });
}
这可能行得通。不习惯使用.管道和.水龙头,但应该可以使用。
请注意,这是一种解决方法,不建议接收和返回
any
。您可以创建一个类似“RequestResponse”的界面,其中包含两个属性:成功和数据。这样,您就可以避免使用
any
type

详细解释您真正需要的内容以及希望在component.html中显示数据的实际结果。但是,当我将'res'更改为'res.data'时,没有任何结果,它将其下划线为红色,并且我得到了另一个错误:类型'Smsmt[]'上不存在任何属性'data'。ts(2339)尝试将'.subscribe(res=>{…}'更改为.subscribe((res:any)=>{…}')。这将删除下划线,并可能解决将服务“getSmsmts()”的返回类型更改为可观察的问题。问题是,该方法返回一个数组,但后端发送一个响应,其中包含一个数组。这就是错误的原因我很抱歉。请让我有点困惑。你能帮我更新代码中的答案吗?是的,我可以,但请稍等,因为我用手机xD让我到办公室,我会解释:)