it-source

각도 2: 유형 오류: AppComponent@4:44의 [{thing.title}]에서 l_thing0이 정의되지 않았습니다.

criticalcode 2023. 11. 7. 20:56
반응형

각도 2: 유형 오류: AppComponent@4:44의 [{thing.title}]에서 l_thing0이 정의되지 않았습니다.

제 앱에 이상한 오류가 발생하고 있습니다.원래는 인쇄를 해야하는데요{{thing.title}}개체에서 온 것이지만 콘솔에 오류가 표시됩니다.

EXCEPTION: TypeError: l_thing0 is undefined in [{{thing.title}} in AppComponent@4:44]

어디에 있는지 잘 모르겠습니다.l_thing0오는 중입니다.보여주려고 하면.{{thing}}페이지에 표시됩니다.[object Object]. 그러려거든요.JSON.stringify(this.thing)(참조)showObj()function), 문자열화된 개체를 올바르게 표시합니다.하지만 만약 내가 이런 속성에 접속하려 한다면,{{thing.title}}나는 오류를 이해합니다.l_thing0정의되지 않았습니다.

app.component.ts:

import {Component, OnInit} from 'angular2/core';
import {Thing} from './thing';
import {ThingService} from './thing.service';
import {SubThingComponent} from "./subthing.component";

@Component({
    selector: 'thing-app',
    template: `
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <h1>{{thing.title}} <a href="#" (click)="showObj()" class="btn btn-default">Show Stringified Obj</a></h1>
                    <subthing></subthing>
                </div>
            </div>
        </div>
    `,
    styles:[`

    `],
    directives: [SubThingComponent],
    providers: [ThingService]
})

export class AppComponent implements OnInit {

    constructor(private _thingService: ThingService) { }

    public thing: Thing;

    showObj() {
        // This correctly shows the stringified object
        alert(JSON.stringify(this.thing));
    }

    getThing() {
        this._thingService.getThing().then(thing => this.thing = thing);
        // This correctly logs the object
        setTimeout(() => {console.log('thing', this.thing)}, 5000);
    }

    ngOnInit() {
        this.getThing();
    }
}

무슨 생각 있어요?

문제는 페이지를 처음 로드할 때thing아직 정의되지 않았습니다. 나중에 비동기식으로 실제 값으로 설정되므로 처음 속성에 액세스하려고 하면 예외가 발생합니다.?elvis operator는 null check의 지름길입니다.

{{thing?.title}}

그러나 일반적으로 다음과 같은 것을 추가하여 실제 개체를 가질 때까지 구성 요소를 렌더링하지 않는 것이 더 좋은 방법입니다.

<h1 *ngIf="thing">

컨테이너로.

파티에 늦게 오긴 하지만 Angular 5를 사용하시는 분들께 도움이 될 것 같아서요.이상하게도 엘비스 교환원이 *ngF 루프에서 일하지 않고 *ngif에서 일할 것이라는 것을 알아챘습니다.여기 이 문제를 해결하기 위한 제 코드가 있습니다.

<div *ngIf = "fullObject?.objProperty">
      <h1>{{fullObject.objProperty1}}</h1>
      <div *ngFor = "let o of fullObject.objPropertyArray">
          <h3>{{o._subheader}}</h3>
          <p>
              {{o._subtext}}
          </p>
        </div>
  </div>
</div>

새 변수를 설정할 수도 있습니다.isFinished로.false서버 또는 비동기 함수에서 데이터를 검색하기 전에 그리고 데이터를 받은 후에 설정합니다.true. 그럼 집어넣습니다.isFinished변화무쌍한*ngIf서버/기능 프로세스가 완료되었는지 확인할 수 있습니까?

저는 Angular 8을 사용하고 있고 데이터가 표시되어 있지만, 저도 이 오류가 있었고 구글링을 통해 이 질문을 하게 되었습니다.(잘 설명되어 있지만) 수용된 답변이 해결되지 않았습니다. (아마도 최신 버전이나 *ngFor와 함께 사용하기 때문일 수 있습니다.) 보다시피 *ngIf를 사용하는 것만으로는 충분하지 않습니다.

오류 발생: v1

  <div class="row">
    <pre>
      <li *ngFor="let obj of object.content">{{obj | json}}</li>
    </pre>
  </div>

오류 발생: v2

  <div class="row" *ngIf="object.content">
    <pre>
      <li *ngFor="let obj of object.content">{{obj | json}}</li>
    </pre>
  </div>

오류 발생: v3

  <div class="row" *ngIf="object.content">
    <pre>
      <li *ngFor="let obj of object?.content">{{obj | json}}</li>
    </pre>
  </div>


오류 없음: v1

  <div class="row">
    <pre>
      <li *ngFor="let obj of object?.content">{{obj | json}}</li>
    </pre>
  </div>

오류 없음: v2

  <div class="row" *ngIf="object?.content">
    <pre>
      <li *ngFor="let obj of object.content">{{obj | json}}</li>
    </pre>
  </div>

오류 없음: v3

  <div class="row" *ngIf="object?.content">
    <pre>
      <li *ngFor="let obj of object?.content">{{obj | json}}</li>
    </pre>
  </div>

언급URL : https://stackoverflow.com/questions/34833358/angular-2-typeerror-l-thing0-is-undefined-in-thing-title-in-appcomponent

반응형