简体   繁体   中英

Angular 2 - [Object Object] - Access the property of the object using dot notation does not work

I know in Angular there are two ways to access object values

Access the property of the object using dot notation (obj.property). Access the property of the object by passing in key value for example obj["property"]

If I output {{ page | json }} , I get an object with all the list.

在此处输入图片说明

If I do ' page.id ' or any property I get an error:

EXCEPTION: Uncaught (in promise): Error: Error in ./PageSingleComponent class PageSingleComponent - inline template:3:6 caused by: undefined is not an object (evaluating 'self.context.page.id')

My component is

import { Component, OnInit } from '@angular/core';
import { Page } from '../page';
import { PageService } from '../page.service';
import { Router, ActivatedRoute, Params } from '@angular/router';

@Component({
  selector: 'app-page-single',
  templateUrl: './page-single.component.html',
  styleUrls: ['./page-single.component.css'],
  providers: [PageService]
})
export class PageSingleComponent implements OnInit {

  page: Page;

  constructor( private pageService: PageService, private route: ActivatedRoute ) { }




  getPost(slug){
  console.log('page slug is',slug);
    this.pageService
      .getPost('other-page')
      .subscribe(res => {
        this.page = res[0];
         console.log('posts inside', res, slug);
      });
  }

  ngOnInit() {

    this.route.params.forEach((params: Params) => {
       let pageSlug = params['pageSlug'];
       this.getPost(pageSlug)
    });

  }

}

Page service

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Page } from './page';

@Injectable()
export class PageService {

  private _wpBase = "http://ecommerce-ux.london/wp-json/wp/v2/";

  constructor(private http: Http) { 
    this.http = http
    this.getPost().subscribe(
        (data) => {
          console.log('posts', data)

        },
        (err) =>  console.log("Error Loging In:",err),
        () => { console.log("All Good With The posts Data")  }
      );




  }

  getPages(): Observable<Page[]> {

      return this.http
        .get(this._wpBase + 'pages')
        .map((res: Response) => res.json());
  }

  getPost(pageSlug): Observable<Page> {

      return this.http
       .get(this._wpBase + `pages?slug=${pageSlug}`)
        .map((res: Response) => res.json());

  }

}

Page-single.component.html

<div>
   <!-- {{ page | json }} works -->
  <h1>{{ page.id  }}</h1>

</div>

Console.log 在此处输入图片说明

Because the page property of your component is not assigned a default value it's not actually defined until the subscribe callback in PageSingleComponent.getPost sets it. This causes an error because you can't access the id property of undefined since it's not an object.

To fix this you need to avoid evaluating the template expression until page has been set. You can do this via ng-if :

<h1 *ngIf=“page”>{{ page.id  }}</h1>

Or you can use the safe navigation operator:

<h1>{{ page?.id  }}</h1>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM