bestsource

'object' 유형의 다른 지원 개체 '[objectObject]'을(를) 찾을 수 없습니다.NgFor는 어레이와 같은 반복 가능한 파일에 대한 바인딩만 지원합니다.

bestsource 2023. 8. 27. 09:43
반응형

'object' 유형의 다른 지원 개체 '[objectObject]'을(를) 찾을 수 없습니다.NgFor는 어레이와 같은 반복 가능한 파일에 대한 바인딩만 지원합니다.

저는 비슷한 질문들을 보았지만, 아무도 저를 도와주지 않았습니다.나는 다음과 같은 물건을 받을 예정입니다.

[
  {
    "id": 1,
    "name": "Safa",
    "email": "neerupeeru@mail.ee",
    "purpose": "thesis",
    "programme": "Software Engineering",
    "year": 2016,
    "language": "Estonian",
    "comments": "In need of correcting a dangling participle.",
    "status": "RECEIVED"
  },
  {
    "id": 2,
    "name": "Safa",
    "email": "neerupeeru@mail.ee",
    "purpose": "thesis",
    "programme": "Software Engineering",
    "year": 2016,
    "language": "Estonian",
    "comments": "In need of correcting a dangling participle.",
    "status": "RECEIVED"
  },
  {
    "id": 3,
    "name": "Salman",
    "email": "neerupeeru@mail.ee",
    "purpose": "thesis",
    "programme": "Software Engineering",
    "year": 2016,
    "language": "Estonian",
    "comments": "In need of correcting a dangling participle.",
    "status": "RECEIVED"
  }
]

다음은 제 http 서비스입니다.

getRequest(){
        return this._http.get("http://consultationwebserver.herokuapp.com/requests").map(res => res.json());
    }

그리고 마지막으로, 나는 다음과 같은 방식으로 서비스를 불렀습니다.

requests;
    constructor(private _http:requestService){}
    ngOnInit(){
        this.requests=this._http.getRequest().subscribe(res=>this.requests=res);
    }

안타깝게도 페이지가 로드되면 다음과 같은 불만이 제기됩니다.

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

그렇다면, 이 코드에 무슨 문제가 있는 걸까요?

사할필없습다니가요용다없니습▁need▁there를 사용할 필요가 .this.requests=만을 때get 콜(으)로 함)requests관찰 가능한 구독이 있음). 가능한 찰할수없응표다니시됩이로 될입니다.success setting ㅠㅠrequests성공에 대한 가치는 의미가 있습니다(이미 하고 있는 일).

this._http.getRequest().subscribe(res=>this.requests=res);

유형과 되면, " 그 도 유 관 오 추 표 니 합 가 다 면 되 시 가 류 래 형 련 과 된 니 다 ▁if ▁add 합 추 가 ▁related , ▁an ▁showsany/RelevantModel구독 매개 변수 개체에 입력합니다.

this._http.getRequest().subscribe(
  (res: any[]) => this.requests =res
);

기본적으로 *ngFor는 배열과 같은 반복 가능한 항목에 대해서만 작동합니다.할당하는 경우this.requests객체 값을 가지려면 *ng을 사용하면 이 오류가 반환됩니다.

들어 을 예들어를, 다같배을선때와 같이 할 때this.myArray = {}이 문제가 발생합니다.그럴 것 같네요.this.myArray = [].

제다한을 합니다.this.requests

ngOnInit(){
  this.requests=this._http.getRequest().subscribe(res=>this.requests=res);
}

로.

ngOnInit(){
  this._http.getRequest().subscribe(res=>this.requests=res);
}

this._http.getRequest()응답 값이 아닌 구독을 반환합니다.은 응값전콜의할해다니당됩백에에 됩니다.subscribe(...)

2행의 책을 배열로 선언할 수 있습니다.

title: any = 'List of books are represted in the bookstore';
books: any = []; 
constructor(private service:  AppService){
}

ngOnInit(){
  this.getBookDetails();
}

getBookDetails() {
    this.service.getBooks().subscribe(books => {
        this.books = books.json();
        console.log(this.books);
    });
}

값 배열 또는 특성 개체를 반환하는 파이프를 만드는 것이 해결책입니다.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'valueArray',
})
export class ValueArrayPipe implements PipeTransform {

  // El parametro object representa, los valores de las propiedades o indice
  transform(objects : any = []) {
    return Object.values(objects);
  }
}

템플릿 구현

<button ion-item *ngFor="let element of element_list | valueArray" >
    {{ element.any_property }}
</button> 

HTTP 응답을 다음과 같이 매핑했기 때문에 동일한 오류가 발생했습니다.

this.http.get(url).map(res => res.json);

내가 실수로 메서드가 아닌 변수처럼 .json을 어떻게 불렀는지 주목하세요.

다음으로 변경:

this.http.get(url).map(res => res.json());

속임수를 썼습니다.

당신의 JSon 파일에서 아래와 같이 변경 부탁드립니다.

 {
    "data":
    [
      {
        "id": 1,
        "name": "Safa",
        "email": "neerupeeru@mail.ee",
        "purpose": "thesis",
        "programme": "Software Engineering",
        "year": 2016,
        "language": "Estonian",
        "comments": "In need of correcting a dangling participle.",
        "status": "RECEIVED"
      },
      {
        "id": 2,
        "name": "Safa",
        "email": "neerupeeru@mail.ee",
        "purpose": "thesis",
        "programme": "Software Engineering",
        "year": 2016,
        "language": "Estonian",
        "comments": "In need of correcting a dangling participle.",
        "status": "RECEIVED"
      },
      {
        "id": 3,
        "name": "Salman",
        "email": "neerupeeru@mail.ee",
        "purpose": "thesis",
        "programme": "Software Engineering",
        "year": 2016,
        "language": "Estonian",
        "comments": "In need of correcting a dangling participle.",
        "status": "RECEIVED"
      }
    ]
    }

그리고 그 이후로는:

 this.http.get(url).map(res:Response) => res.json().data);

데이터는 실제로 json 파일의 tge 컬렉션 이름입니다.위의 코드를 사용해 보십시오, 작동할 것이라고 확신합니다.

아래와 같은 json 형식의 개체 위에 반복하려면

{
  "mango": { "color": "orange", "taste": "sweet" }
  "lemon": { "color": "yellow", "taste": "sour" }
}
  1. 변수에 할당

    let rawData = { "mang":{...}, "lemon": {...} }

  2. 값 또는 키를 보관할 빈 배열을 만듭니다.

    let dataValues = []; //For values

    let dataKeys = []; //For keys

  3. 키를 반복하고 값(및 키)을 변수에 추가합니다.

    for(let key in rawData) { //Pay attention to the 'in' dataValues.push(rawData[key]); dataKeys.push(key); }

  4. 이제 *ngFor 또는 for 루프에서 사용할 수 있는 키 및 값 배열이 있습니다.

    for(let d of dataValues) { console.log("Data Values",d); }

    <tr *ngFor='let data of dataValues'> ..... </tr>

이가 발생한 는 Google의 하십시오.*ngFor지시가 정확합니다.은 제가 이 하는 데 오랜 시간이 걸렸다는 것을 합니다.*ngForng-template내 구성요소 대신 요소를 반복하고 싶었습니다.

틀렸습니다

<ng-template *ngFor=let group of groups$ | async" ...>
  <my-component [prop1]="group.key" ... </my-component>
<\ng-template>

맞아요.

<my-component *ngFor=let group of groups$ | async" [prop1]="group.key" ... </my-component>

저는 이것이 나중에 생각했을 때 명백한 실수라는 것을 알지만, 저는 여기에 있는 대답이 제가 지금 가지고 있는 두통을 누군가를 구해줄 수 있기를 바랍니다.

저도 같은 문제가 있습니다.이것이 제가 문제를 해결한 방법입니다.먼저 오류가 발생했을 때, 내 어레이 데이터는 DB에서 이렇게 오고 있습니다 --,

{brands: Array(5), _id: "5ae9455f7f7af749cb2d3740"} 

데이터가 배열을 포함하는 개체가 아니라 배열인지 확인합니다.배열만 이렇게 보입니다 --,

(5) [{…}, {…}, {…}, {…}, {…}]

그것은 제 문제를 해결했습니다.

비동기 파이프를 사용해야 합니다.문서: https://angular.io/api/common/AsyncPipe

예:

<li *ngFor="let a of authorizationTypes | async"[value]="a.id">
     {{ a.name }}
</li>

저는 같은 문제에 직면했습니다.

나의 첫번째 아들

{"items":

         [
           {"id":1,
            "Name":"test4"
           },
           {"id":2,
            "Name":"test1"
           }
         ]
}

나는 [] 안에서 내 아들을 바꿨습니다.

[{"items":

         [
           {"id":1,
            "Name":"test4"
           },
           {"id":2,
            "Name":"test1"
           }
         ]
}]

this.requests=res객체에 과 같은 을 할당하려고 .

{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK",
"url":"xyz","ok":true,"type":4,"body":[{}]}

때문에, 형 식 다 형 때 기 입 니 르 과 식 응 답 하 할 는 이 야 해 당 ▁format ▁since ▁format 니 입 다 때 ▁you 문 ▁is ▁response ▁haveres.body필요한 내용을 얻기 위해 응답에서 일부를 삭제합니다.

<ul>
<li *ngFor = "let Data of allDataFromAws  | async">
  <pre> {{ Data | json}}</pre>
</li>
</ul>

비동기를 사용하여 모든 DataFromAws를 ArrayObject로 변환...

var를 데이터를 보유한 배열로 선언하면 됩니다. 저한테는 효과가 있었습니다.

listingdata:Array<any> = [];
this.listingdata = data.results.rows;

html 페이지의 목록 데이터를 루프합니다.

여기 해결책이 있습니다.

데이터베이스에서 배열을 수신하는 경우.배열 데이터를 변수 내부에 저장하지만 변수는 개체로 정의됩니다.이번에는 오류가 발생합니다.

데이터베이스에서 배열을 수신하고 있으며 변수 '배너 슬라이더' 내부에 배열을 기록하고 있습니다.이제 '임의 슬라이더' 유형은 '임의'이지만, '임의 슬라이더'라고 쓰면 목적어가 됩니다.배너 슬라이더와 마찬가지입니다. any={}.따라서 이번에는 객체 유형 변수 내부에 배열 데이터를 저장합니다.그래서 당신은 그 오류를 발견합니다.

따라서 '임의의 슬라이더:any;' 또는 '임의 슬라이더:any=[]'와 같은 변수를 작성해야 합니다.

여기서 저는 예를 들겠습니다.

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
bannersliders:any;
  getallbanner(){
    this.bannerService.getallbanner().subscribe(data=>{
      this.bannersliders =data;
   })
  }

에서 Angular와 함께 스프링 부트를 사용합니다. 기본값을 작성할지 여부를 확인하십시오.

결과를 JSON 객체로 구문 분석: JSON.prase(result.arrayOfObjects) *************

저는 이 문제에 직면한 후 이 페이지에 왔습니다.그래서 저의 문제는 서버가 문자열 형태의 객체 배열을 보내는 것이었습니다.이는 다음과 같습니다.

서버에서 가져온 후 콘솔에 결과를 인쇄하면 문자열입니다.

'arrayOfObject': '[
                  {'id': '123', 'designation': 'developer'},
                  {'id': '422', 'designation': 'lead'}
               ]'

그래서 나는 이 문자열을 서버에서 받은 후에 JSON으로 변환해야 합니다.서버에서 받은 결과 문자열을 구문 분석하는 방법을 사용합니다.

JSON.parse(result.arrayOfObjects)
Store that objects into Array  and then iterate the Array
export class AppComponent {

 public obj: object =null;
 public myArr=[];

  constructor(){

    this.obj = {
      jon : {username: 'Jon', genrePref: 'rock'},
      lucy : {username: 'Lucy', genrePref: 'pop'},
      mike : {username: 'Mike', genrePref: 'rock'},
      luke : {username: 'Luke', genrePref: 'house'},
      james : {username: 'James', genrePref: 'house'},
      dave : {username: 'Dave', genrePref: 'bass'},
      sarah : {username: 'Sarah', genrePref: 'country'},
      natalie : {username: 'Natalie', genrePref: 'bass'}
  }
  }
  ngOnInit(){
    this.populateCode();
  }

  populateCode(){
    for( let i in this.obj) {   //Pay attention to the 'in'
    console.log(this.obj[i]);
    this.myArr.push(this.obj[i]);
  }
  }
 }



<div *ngFor="let item of myArr ">
    {{item.username}}
    {{item.genrePref}}
  </div>

누군가 저와 같은 결과를 얻을 수 있을지도 모르고, 왜 이런 일이 일어나는지도 모르겠습니다(아마도 버그일 것인가?). 하지만 사실 이런 각 오버레이에 대한 구성 요소 포털을 만들려고 했기 때문에 이러한 오류가 발생했습니다.

const smartfillPortal = new ComponentPortal(
  SmartFillModalComponent,
  this.viewContainerRef,
  {
    get: () => this.smartfillOverlayRef,
  }
);

로 변경

const smartfillPortal = new ComponentPortal(SmartFillModalComponent);

어떤 이유에서인지 수정했습니다(오버레이에 대한 정보도 누락된 것 같습니다).

이상한 것은 오버레이 코드에 있는 것과 같은 것도 있습니다.

<div class="flex" *ngFor="let i of [1,2,3]; let i = index">
  <span>hi there</span>
</div>

결과적으로

Error: Cannot find a differ supporting object '1,2,3' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

enter image description here

속성에 액세스하는 방법을 변경할 수도 있습니다.이 문제에 직면했고 액세스하는 대신 다음을(를 사용했습니다.

이것. 약간의 서비스. 세부 정보

사용한 적이 있습니다.

이.일부 서비스['details'];

이것이 저에게 이 오류를 해결해 주었습니다.

저는 *ngFor에 인덱스를 추가했을 때 오류가 해결되었습니다.

<tr *ngFor = "let element of element_list; let i=index">
             <td>{{element.id}}</td>
             <td>{{element.status}}</td>
             <td>{{element.name}}</td>
 </tr>

언급URL : https://stackoverflow.com/questions/39819392/cannot-find-a-differ-supporting-object-object-object-of-type-object-ngfor

반응형