Generating Angular services

Angular uses services to communicate with backend APIs, so it is important to understand this and use Angular CLI to generate code for this. There are two main backend APIs that need to be accessed via Angular services in our application. One is Tweets and the other is Users. So, we shall generate those using the following commands:

ng g s tweets

This will generate a tweets.service.ts file under the /src/app directory, but for simplicity of development, it should be moved to a new directory under /src/app/shared/tweets for better grouping and structure.

The tweets.service.ts file looks like the following after modifying the stub code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { AuthService } from '../../auth.service';

@Injectable()
export class TweetsService {
public API = '//localhost:8080';
public TWEETS_API = this.API + '/tweets';
private authService;

constructor(private http: HttpClient, authService: AuthService) {
this.authService = authService;
}

getAll(): Observable<any> {
let headers = new HttpHeaders().set('Authorization', 'Bearer
'+this.authService.getToken());
return this.http.get(this.TWEETS_API, {headers: headers});
}

save(tweet: any): Observable<any> {
let headers = new HttpHeaders().set('Authorization', 'Bearer
'+this.authService.getToken());
let result: Observable<Object>;
result = this.http.post(this.TWEETS_API, tweet, {headers:
headers});
return result;
}

}

TweetsService will use HttpClient to retrieve tweets and save tweets using the backend API, with the standard REST GET and POST methods. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.214.60