I have very recently started trying to work with Angular 2 and am stuck on trying to add JSON data to a service. I've run through the official tutorial and the documentation about HTTP requests, but can't seem to get this to work. The base code for the service is as follows -
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Address } from './models/address';
const AddressEndpoint = 'https://jsonplaceholder.typicode.com/users';
@Injectable()
export class AddressService {
constructor(private http: HttpClient) { }
getAll(): Observable<Address[]> {
throw new Error('NOT IMPLEMENTED');
}
get(id: number): Address {
throw new Error('NOT IMPLEMENTED');
}
insert(addr: Address) {
throw new Error('NOT IMPLEMENTED');
}
remove(id: number) {
throw new Error('NOT IMPLEMENTED');
}
How do I access the AddressEndpoint const within each of the class methods and how do I specific which piece of data I want to GET for each request? I I then need to feed this to an Address model with the following code and am again a bit unclear as to how I'd push my pulled data here.
export class Address {
id: number;
name: string;
address: {
street?: string,
suite?: string,
city?: string,
zipcode?: string
};
}
It's somewhat hard to answer as there is little information regarding the structure of the JSON, how the data is structured, and what data you expect to retrieve with each method stubbed in AddressService
.
An option for accessing a common property would be to simply use a class property, such as a readonly
one, on AddressService, that you can access the value using this
within any of the AddressService
class methods:
@Injectable()
export class AddressService {
readonly AddressEndpoint = 'https://jsonplaceholder.typicode.com/users';
constructor(private http: HttpClient) { }
get(id: number): Observable<Address> {
return this.http.get(`${this.AddressEndpoint}/${id}`);
}
}
In terms of mapping the result to a type/model, such as Address
in your case, you can typecheck the response with HttpClient
as follows:
get(id: number): Observable<Address> {
return this.http.get<Address>(`${this.AddressEndpoint}/${id}`);
}
Otherwise, you can utilize the rjxs map
operator to transform the response to the Address
type/model as need before some class subscribe()
to it:
get(id: number): Observable<Address> {
return this.http.get(`${this.AddressEndpoint}/${id}`).map(data => new Address(data['someProperty'], data['someOtherProperty']);
}
Note: If you using @angular/cli and will be using HttpClient
to execute something like a get()
to a JSON file located alongside this AddressService
, you will want to add the file to the assets
array property of angular-cli.json
.
Hopefully that helps!