When it comes to Angular, there are two methods for accessing object values:
1. Access the property of the object using dot notation (obj.property).
2. Access the property of the object by passing in a key value pair, for example obj["property"].
If I display {{ page | json }}, I can see an object containing all the list items.
https://i.sstatic.net/UWKi4.png
If I try 'page.id' or any other property, I encounter 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')
This is my component:
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)
});
}
}
My 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 https://i.sstatic.net/kHICT.png