Angular - convert HAL to JSON - json

The following service extracts category objects from a REST service which returns them in HAL format. Now I try to convert that response into JSON. For that I searched and tried different solutions, e.g. chariotsolutions or so. Some are based on Response from '#angular/http' which is deprecated and which I cannot make work.
How can I do the conversion?
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable } from 'rxjs/Rx';
import { of } from 'rxjs/observable/of';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
import { Category } from './category';
#Injectable()
export class CategoryService {
private categoriesUrl = 'http://localhost:8080/account/categories';
constructor(private http: HttpClient) { }
getCategories(): Observable<Category[]> {
return this.http.get<Category[]>(this.categoriesUrl);
}
}
The response as HAL
{
"_embedded": {
"categories": [
{
"id": 1,
"name": "hardware",
"description": "comprises all computer hardware",
"level": "FIRST",
"_links": {
"self": {
"href": "http://localhost:8080/account/categories/1"
},
"categoryEntity": {
"href": "http://localhost:8080/account/categories/1"
}
}
},
{
"id": 2,
"name": "hardware_notebook",
"description": "all notebooks",
"level": "SECOND",
"_links": {
"self": {
"href": "http://localhost:8080/account/categories/2"
},
"categoryEntity": {
"href": "http://localhost:8080/account/categories/2"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/account/categories{?page,size,sort}",
"templated": true
},
"profile": {
"href": "http://localhost:8080/account/profile/categories"
}
},
"page": {
"size": 20,
"totalElements": 8,
"totalPages": 1,
"number": 0
}
}

getCategories(): Observable<Category[]> {
return this.http.get<Category[]>(this.categoriesUrl)
.map((result:any)=>{
console.log(result); //<--it's an object
//result={"_embedded": {"categories": [..]..}
return result._embedded.categories; //just return "categories"
});
}
With Rjxs 6.0 we must use pipe(map)
getCategories(): Observable<Category[]> {
return this.http.get<Category[]>(this.categoriesUrl).pipe(
map((result:any)=>{
console.log(result); //<--it's an object
//result={"_embedded": {"categories": [..]..}
return result._embedded.categories; //just return "categories"
}));
}

Try following:
getCategories(): Observable<Category[]> {
return this.http.get<Category[]>(this.categoriesUrl).map((response)=>{
return response;
})
}

Related

Angular unable to display API results in html

In Angular, why am I unable to display the results from an API call?
The JSON returned from the API call. I want to display the value attribute.
{
"data": [
{
"type": "fuzzycompletions",
"attributes": {
"value": "APALE"
},
"relationships": {
"lei-records": {
"data": {
"type": "lei-records",
"id": "9695006WHN4DWDKBF403"
},
"links": {
"related": "https://api.gleif.org/api/v1/lei-records/9695006WHN4DWDKBF403"
}
}
}
},
{
"type": "fuzzycompletions",
"attributes": {
"value": "APPLITEC"
}
},
{
"type": "fuzzycompletions",
"attributes": {
"value": "AppLogic"
},
"relationships": {
"lei-records": {
"data": {
"type": "lei-records",
"id": "724500S2JQ8M9Q67N911"
},
"links": {
"related": "https://api.gleif.org/api/v1/lei-records/724500S2JQ8M9Q67N911"
}
}
}
},
{
"type": "fuzzycompletions",
"attributes": {
"value": "APPRECIO"
},
"relationships": {
"lei-records": {
"data": {
"type": "lei-records",
"id": "969500ZFBM0TC2T1HV85"
},
"links": {
"related": "https://api.gleif.org/api/v1/lei-records/969500ZFBM0TC2T1HV85"
}
}
}
},
{
"type": "fuzzycompletions",
"attributes": {
"value": "AMPLEGEST"
},
"relationships": {
"lei-records": {
"data": {
"type": "lei-records",
"id": "969500DYMLRK8URCGP47"
},
"links": {
"related": "https://api.gleif.org/api/v1/lei-records/969500DYMLRK8URCGP47"
}
}
}
},
{
"type": "fuzzycompletions",
"attributes": {
"value": "ANPLEX OÜ"
},
"relationships": {
"lei-records": {
"data": {
"type": "lei-records",
"id": "254900RNJSFWJXOZE551"
},
"links": {
"related": "https://api.gleif.org/api/v1/lei-records/254900RNJSFWJXOZE551"
}
}
}
},
{
"type": "fuzzycompletions",
"attributes": {
"value": "Apleks OÜ"
},
"relationships": {
"lei-records": {
"data": {
"type": "lei-records",
"id": "254900VZB706EXH22533"
},
"links": {
"related": "https://api.gleif.org/api/v1/lei-records/254900VZB706EXH22533"
}
}
}
},
{
"type": "fuzzycompletions",
"attributes": {
"value": "APPLE-WAY"
},
"relationships": {
"lei-records": {
"data": {
"type": "lei-records",
"id": "969500QV2N8IIVULLH93"
},
"links": {
"related": "https://api.gleif.org/api/v1/lei-records/969500QV2N8IIVULLH93"
}
}
}
},
{
"type": "fuzzycompletions",
"attributes": {
"value": "APPLICOMM"
},
"relationships": {
"lei-records": {
"data": {
"type": "lei-records",
"id": "969500MCJ58VYVTX3715"
},
"links": {
"related": "https://api.gleif.org/api/v1/lei-records/969500MCJ58VYVTX3715"
}
}
}
},
{
"type": "fuzzycompletions",
"attributes": {
"value": "APPLIQ AS"
},
"relationships": {
"lei-records": {
"data": {
"type": "lei-records",
"id": "8945006S1SZMS8HKLR20"
},
"links": {
"related": "https://api.gleif.org/api/v1/lei-records/8945006S1SZMS8HKLR20"
}
}
}
}
]
}
I have a service.ts file for connecting to the API
import { HttpClient} from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class GleifService {
private gleifUrl = 'https://api.gleif.org/api/v1/fuzzycompletions?field=entity.legalName&q='; // URL to web api
private data:any = []
constructor(private http: HttpClient) {}
getGleif(name: string){
const url = `${this.gleifUrl}${name}`;
this.http.get(url).subscribe((res)=>{
this.data = res
console.log(this.data)
})
}
}
A component.ts file
import { Component, OnInit } from '#angular/core';
import { GleifService } from '../gleif.service';
#Component({
selector: 'app-security',
templateUrl: './security.component.html',
styleUrls: ['./security.component.css']
})
export class SecurityComponent implements OnInit {
// array for storing the data
private data:any = []
constructor(private gleifService: GleifService) { }
getGleif(name: string): void {
this.data = this.gleifService.getGleif(name);
}
ngOnInit() {
this.getGleif(name);
}
}
And a .html file for displaying the results
<div>
<label>Company ID:
<input placeholder="Autofill"/>
</label>
</div>
<div>
<label>Company Name:
<input #Name placeholder="A Company Ltd"/>
<button (click)="getGleif(Name.value); Name.value=''">Search</button>
</label>
</div>
<div *ngFor="let entry of data?.data" style="text-align:center">
<h3>
header works: {{ entry.type }}
</h3>
</div>
I can see the results in the console response. How can I access and display results from the API call?
It is because you are subscribing your http call from your service instead of returning it's data. Once you have subscribed the call in your service, no data will be returned unless you return the observable value from your http and let the component subscribe it's response or data
Update your code instead to:
Service
import { Observable } from 'rxjs';
...
getGleif(name: string): Observable<any> {
const url = `${this.gleifUrl}${name}`;
return this.http.get(url);
}
Component
...
getGleif(name: string): void {
this.gleifService
.getGleif(name)
.subscribe(res => this.data = res);
}
or in your Component you could also do this:
...
data$: Observable<any>;
getGleif(name: string): void {
this.data$ = this.gleifService.getGleif(name); // we have assigned it with an Observable variable since the return of this service is of Observable type that needed to be subscribe into
}
Template
...
// Since the data$ is async, we use pipe async to fetch it's raw data
<div *ngFor="let entry of (data$ | async)?.data" style="text-align:center">
...
</div>
make sure to return the data from the service and subscribe inside the component file.
and you don't need to call the function inside ngOnInit because you are going to call it when search button is clicked.
componet.ts file
import { Component } from "#angular/core";
import { GleifService } from "./service";
#Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
// array for storing the data
private data: any = [];
constructor(private gleifService: GleifService) {}
getGleif(name: string): void {
this.gleifService.getGleif(name).subscribe((response: any) => {
this.data = response.data;
});
}
}
component.html file
<div>
<label
>Company ID:
<input placeholder="Autofill" />
</label>
</div>
<div>
<label
>Company Name:
<input #Name placeholder="A Company Ltd" />
<button (click)="getGleif(Name.value); Name.value=''">Search</button>
</label>
</div>
<div *ngFor="let entry of data" style="text-align: center;">
<h3>
header works: {{ entry.type }}
</h3>
</div>
service.ts file
import { HttpClient } from "#angular/common/http";
import { Injectable } from "#angular/core";
#Injectable({
providedIn: "root"
})
export class GleifService {
private gleifUrl =
"https://api.gleif.org/api/v1/fuzzycompletions?field=entity.legalName&q="; // URL to web api
constructor(private http: HttpClient) {}
getGleif(name: string) {
const url = `${this.gleifUrl}${name}`;
return this.http.get(url);
}
}
working codesandbox
Maybe you need to subscribe to the result in the component.ts file
getGleif(name: string): void {
this.gleifService.getGleif(name).subscribe((result) => {
this.data = result
});
}

Unable to Parse JSON data in angular requested through API

I am trying to get the data of movie from imdb site with the help of an API but unable to process the data further.
Here is the link i pass ("https://sg.media-imdb.com/suggests/j/johnwick.json") in the get method and opening the browser it looks like this:
imdb$johnwick({
"v": 1,
"q": "johnwick",
"d": [
{
"l": "John Wick: Chapter 3 - Parabellum",
"id": "tt6146586",
"s": "Keanu Reeves, Ian McShane",
"y": 2019,
"q": "feature",
"vt": 5,
"i": [
"https://m.media-amazon.com/images/M/MV5BNDU3YzJlY2EtODA3NS00ZWM3LWJhYjUtZWE3MmE2YmEzNWYwXkEyXkFqcGdeQXVyNDMzMzI5MjM#._V1_.jpg",
4050,
6000
],
"v": [
{
"l": "Official Trailer",
"id": "vi3978017305",
"s": "2:18",
"i": [
"https://m.media-amazon.com/images/M/MV5BNTg2YzEyNjktMmRmZi00NjU4LWIxNzYtMGE0Y2U2MDI5Y2Q1XkEyXkFqcGdeQW1yb3NzZXI#._V1_.jpg",
1920,
1080
]
}
]
},
{
"l": "John Wick",
"id": "tt2911666",
"s": "Keanu Reeves, Michael Nyqvist",
"y": 2014,
"q": "feature",
"vt": 23,
"i": [
"https://m.media-amazon.com/images/M/MV5BMTU2NjA1ODgzMF5BMl5BanBnXkFtZTgwMTM2MTI4MjE#._V1_.jpg",
1365,
2048
],
"v": [
{
"l": "Trailer #2",
"id": "vi2273816345",
"s": "1:00",
"i": [
"https://m.media-amazon.com/images/M/MV5BMjU0OTQwMjUyN15BMl5BanBnXkFtZTgwODQ5OTE4MjE#._V1_.jpg",
640,
480
]
},
{
"l": "Clip",
"id": "vi3905924889",
"s": "0:29",
"i": [
"https://m.media-amazon.com/images/M/MV5BNDYwMTUwNTMyNF5BMl5BanBnXkFtZTgwNDcyMjExMzE#._V1_.jpg",
1280,
720
]
},
{
"l": "John Wick",
"id": "vi2809377049",
"s": "4:18",
"i": [
"https://m.media-amazon.com/images/M/MV5BNGQ1YjYwOTUtODRkOS00NjU3LWJjZTMtOWM1MWE2YmFiN2ZjXkEyXkFqcGdeQXVyNzU1NzE3NTg#._V1_.jpg",
480,
360
]
}
]
},
{
"l": "John Wick: Chapter 2",
"id": "tt4425200",
"s": "Keanu Reeves, Riccardo Scamarcio",
"y": 2017,
"q": "feature",
"i": [
"https://m.media-amazon.com/images/M/MV5BMjE2NDkxNTY2M15BMl5BanBnXkFtZTgwMDc2NzE0MTI#._V1_.jpg",
1328,
2048
]
},
{
"l": "John Williams",
"id": "nm0002354",
"s": "Music Department, Star Wars: Episode I - The Phantom Menace (1999)",
"i": [
"https://m.media-amazon.com/images/M/MV5BMjY5MTgzMTQ1NF5BMl5BanBnXkFtZTYwNDg3OTcz._V1_.jpg",
280,
400
]
},
{
"l": "John Witherspoon",
"id": "nm0936762",
"s": "Actor, Friday (1995)",
"i": [
"https://m.media-amazon.com/images/M/MV5BMTM2NTg4MDcxNV5BMl5BanBnXkFtZTYwMDAxMzY0._V1_.jpg",
317,
400
]
},
{
"l": "John Williams",
"id": "nm0002369",
"s": "Actor, Sabrina (1954)",
"i": [
"https://m.media-amazon.com/images/M/MV5BMTUyNDg1MTU5MV5BMl5BanBnXkFtZTcwMTgwNTUxOA##._V1_.jpg",
1107,
1426
]
},
{
"l": "John Wilder",
"id": "nm0928588",
"s": "Writer, Centennial (1978-1979)",
"i": [
"https://m.media-amazon.com/images/M/MV5BMjAxNjE0NzE1MV5BMl5BanBnXkFtZTcwNzUzNjI0NA##._V1_.jpg",
473,
650
]
},
{
"l": "John Wick Chapter 2: Wick-vizzed",
"id": "tt7161870",
"s": "Pedro Hollywood, J.J. Perry",
"y": 2017,
"q": "video",
"i": [
"https://m.media-amazon.com/images/M/MV5BNDNkZDI0MjktMmZiYS00ZjI4LWI3ZDctMTBhMTMyYjczMDhlXkEyXkFqcGdeQXVyODA1NjQ0OTY#._V1_.jpg",
2000,
3000
]
}
]
})
Here is my angular code (The service file):
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class MovieProviderService {
storeMovie: any[];
constructor(private http: HttpClient) { }
getmovies(): Observable<any>
{
return this.http.get('https://sg.media-imdb.com/suggests/j/johnwick.json');
}
}
The below code is the file getting served:
import { Component, OnInit } from '#angular/core';
import { MovieProviderService } from '../movie-provider.service';
#Component({
selector: 'app-movie-container',
templateUrl: './movie-container.component.html',
styleUrls: ['./movie-container.component.scss']
})
export class MovieContainerComponent implements OnInit {
constructor(private movieService: MovieProviderService) { }
ngOnInit() {
let obs = this.movieService.getmovies();
obs.subscribe(
(response)=>{
const data = response.json();
console.log(data);},
(error)=>{console.log(error)}
)
}
}
It is giving the parsing error on console of chrome like unable to parse JSON at position 0...
I can see that the JSON data is contained inside imdb$johnwick( JSON ). How to get rid of that or may be tell some other good way or some topics which i need to learn. THANKYOU
IMDB return data in JSONP format so here you need to import HttpClientModule and HttpClientJsonpModule into your module.
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
// Import relevant http modules
import { HttpClientModule, HttpClientJsonpModule } from '#angular/common/http';
import { AppComponent } from './app.component';
import { ExampleService } from './example.service';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
// Import relevant http modules
HttpClientModule,
HttpClientJsonpModule
],
providers: [ExampleService],
bootstrap: [AppComponent]
})
export class AppModule { }
model-provider.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class MovieProviderService {
storeMovie: any[];
constructor(private http: HttpClient) { }
getmovies(): Observable<any>
{
return this.http.jsonp('https://sg.media-imdb.com/suggests/j/johnwick.json', 'callback');
}
}
Hope this will help!
In the service.js pass the option to handle the response as "text". We want to handle the reformatting of the text response in the service so we do not need to account for this in every component.
Using /(?:^.*?(\{)|\)$)/gm replaces everything before the first { and the ending ). The gm is "global" and "multi-line" for matching and will only replace the text if these rules are matched. We will then replace with first capture group of the RegExp (if there is no capture group one $1 becomes a blank string).
I took this approach to ensure if the source passes valid JSON in the future we wont be breaking/replacing valid JSON.
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class MovieProviderService {
storeMovie: any[];
constructor(private http: HttpClient) { }
getmovies(): Observable<string>
{
return this.http.get('https://sg.media-imdb.com/suggests/j/johnwick.json', { responseType: 'text' })
.map((res) => {
return JSON.parse(res.replace(/(?:^.*?(\{)|\)$)/gm, "$1"));
});
}
}
import { Component, OnInit } from '#angular/core';
import { MovieProviderService } from '../movie-provider.service';
#Component({
selector: 'app-movie-container',
templateUrl: './movie-container.component.html',
styleUrls: ['./movie-container.component.scss']
})
export class MovieContainerComponent implements OnInit {
constructor(private movieService: MovieProviderService) { }
ngOnInit() {
let obs = this.movieService.getmovies();
obs.subscribe(
(response)=>{
const data = response; // no longer need to call .json()
console.log(data);},
(error)=>{console.log(error)}
)
}
}

Angular map function is returning "undefined is not a function"

I'm following this tutorial https://www.barbarianmeetscoding.com/blog/2016/04/02/getting-started-with-angular-2-step-by-step-6-consuming-real-data-with-http/, with Angular2 and VS Code.
I created a db.json server to test an api with, with the test data looking like
{
"articles": [{
"id": 1,
"name": "Wand of Lightning",
"description": "A powerful wand of ligthning.",
"price": 50,
"imageUrl": "/assets/images/wand.png",
"specs": [{
"name": "weight",
"value": 10
}, {
"name": "height",
"value": 22
}, {
"name": "material",
"value": "wood"
}],
"reviews": [{
"author": "Jaime",
"title": "I loved it!",
"content": "I loved the wand of ligthning! I usually use it to charge my laptop batteries!",
"rating": 5
}, {
"author": "John Doe",
"title": "Underwhelming",
"content": "I didn't like it at all...",
"rating": 1
}]
}, {
"id": 2,
"name": "Staff of Fire",
"description": "A powerful staff of fire.",
"price": 150,
"imageUrl": "/assets/images/staff-of-fire.png",
"specs": [{
"name": "weight",
"value": 10
}, {
"name": "height",
"value": 22
}, {
"name": "material",
"value": "wood and alabaster"
}],
"reviews": [{
"author": "Jaime",
"title": "I loved it!",
"content": "I loved the wand of ligthning! I usually use it to charge my laptop batteries!",
"rating": 5
}, {
"author": "John Doe",
"title": "Underwhelming",
"content": "I didn't like it at all...",
"rating": 1
}]
}
Now if I try to adapt my code to the sample, I get
undefined is not a function
Here's items.component.ts
import { Component, OnInit } from '#angular/core';
import {ItemsService} from '../items.service';
import {Item} from '../item';
#Component({
selector: 'app-items',
templateUrl: './items.component.html',
styleUrls: ['./items.component.css']
})
export class ItemsComponent implements OnInit {
items: Item[] = [];
errorMessage: string = '';
isLoading: boolean = true;
constructor(private itemsService: ItemsService) { }
ngOnInit() {
this.itemsService
.getAll().
subscribe(
p => this.items =p,
e => this.errorMessage = e,
/* onCompleted */ () => this.isLoading = false
)
}
}
items.service.ts
import { Injectable } from '#angular/core';
import { Http, Response, RequestOptions, Headers } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import {Item} from './item';
#Injectable()
export class ItemsService {
private baseUrl: string ='http://localhost:3000';
constructor(private http: Http) {
}
getAll(): Observable<Item[]>{
let items = this.http
.get(`${this.baseUrl}/articles`, { headers: this.getHeaders()})
.map(this.mapItems)
.catch(this.handleError);
return items;
}
private getHeaders(){
let headers = new Headers();
headers.append('Accept', 'application/json');
return headers;
}
mapItems(response:Response): Item[]{
return response.json().map(this.toItem)
}
toItem(r:any): Item{
let result = <Item>({
id: r.id,
name: r.name,
description: r.description,
price: r.price,
imageUrl: r.imageUrl,
});
console.log('Parsed item:', result);
return result;
}
// this could also be a private method of the component class
handleError (error: any) {
// log error
// could be something more sofisticated
let errorMsg = error.message || `Yikes! There was a problem with our hyperdrive device and we couldn't retrieve your data!`
console.error(errorMsg);
// throw an application level error
return Observable.throw(errorMsg);
}
}
Note: making
return response.json().map(this.toItem)
Into
return response.json()
works. But I would like to get map working.
EDIT: Screenshot
this will solve your issue -
getAll(): Observable<Item[]> {
const items = this.http
.get(`${this.baseUrl}/articles`, {headers: this.getHeaders()})
.map((response: Response) => this.mapItems(response.json()))
.catch(this.handleError);
return items;
}
mapItems(data: Array<any>): Item[] {
return data.map(item => this.toItem(item));
}
I think what you want to map (Array.prototype.map) is the articles in your response object, and not the object itself. Do this:
mapItems(response:Response): Item[]{
return response.json().articles.map(this.toItem)
}

AngularJS 2 : Getting data from json file not working

I am trying to get the json data from an Angular service hero.service.ts. When using the fake http API inMemoryDataService, everything works fine and I am getting the json data from the in-memory-data.service.ts file. But when I try to get the data from a real json file, it does not work and I am getting an error 'collection not found' in the browser.
Here are the files contents (all 3 files are located in the app/ folder):
hero.service.ts :
import { Injectable } from '#angular/core';
import { Headers, Http , Response} from '#angular/http';
import 'rxjs/add/operator/toPromise';
import { Hero } from './hero';
#Injectable()
export class HeroService {
private heroesUrl = 'app/fakeListOfHeroes'; // URL to web api
//private heroesUrl = 'app/heroes.json'; // URL to JSON file
constructor(private http: Http) { }
getHeroes(): Promise<Hero[]>
{
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data)
.catch(this.handleError);
}
private handleError(error: any)
{
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
hero.service.ts :
export class InMemoryDataService {
createDb() {
let fakeListOfHeroes = [
{id: 11, name: 'Mr. Nice'},
{id: 12, name: 'Narco'},
{id: 13, name: 'Bombasto'},
{id: 14, name: 'Celeritas'},
{id: 15, name: 'Magneta'},
{id: 16, name: 'RubberMan'},
{id: 17, name: 'Dynama'},
{id: 18, name: 'Dr IQ'},
{id: 19, name: 'Magma'},
{id: 20, name: 'Tornado'}
];
return {fakeListOfHeroes};
}
}
heroes.json :
{
"data": [{
"id": 11,
"name": "Mr. Nice"
}, {
"id": 12,
"name": "Narco"
}, {
"id": 13,
"name": "Bombasto"
}, {
"id": 14,
"name": "Celeritas"
}, {
"id": 15,
"name": "Magneta"
}, {
"id": 16,
"name": "RubberMan"
}, {
"id": 17,
"name": "Dynama"
}, {
"id": 18,
"name": "Dr IQ"
}, {
"id": 19,
"name": "Magma"
}, {
"id": 20,
"name": "Tornado"
}]
}
Error in the browser:
error in browser
Any help would be appreciated. Thanks!
Found it ! It was due to the InMemoryBackendService and InMemoryDataService used in main.ts file, that seem to 'redirect' the calls from http.get method. Commenting those lines from main.ts file resolved the issue :
// Imports for loading & configuring the in-memory web api
import { XHRBackend } from '#angular/http';
//import { InMemoryBackendService, SEED_DATA } from 'angular2-in-memory-web-api';
//import { InMemoryDataService } from './in-memory-data.service';
// The usual bootstrapping imports
import { bootstrap } from '#angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '#angular/http';
import { AppComponent } from './app.component';
import { appRouterProviders } from './app.routes';
bootstrap(AppComponent, [
appRouterProviders,
HTTP_PROVIDERS
/*,
{ provide: XHRBackend, useClass: InMemoryBackendService }, // in-mem server
{ provide: SEED_DATA, useClass: InMemoryDataService } // in-mem server data
*/
]);

Ember Data: Using "links" on JSON payload for hasMany relationships

Given two models in an app using DS.RESTAdapter:
App.Calendar = DS.Model.extend({
reservations: DS.hasMany("reservation", { async: true })
});
App.Reservation = DS.Model.extend({
date: DS.attr("date"),
calendar: DS.belongsTo("calendar")
});
And payloads such as:
/api/calendar/1:
{
"calendar": {
"id": 1,
"reservations": [],
"links": {
"reservations": "/api/calendar/1/reservations"
}
}
}
/api/calendar/1/reservations:
{
"reservations": [
{
"id": 1,
"date": "10/01/2014"
}
]
}
Why is it that the reservations array on the Calendar model isn't being lazy-loaded?
Your json shouldn't have reservations defined twice
{
"calendar": {
"id": 1,
"links": {
"reservations": "/api/calendar/1/reservations"
}
}
}