Generating the users service

This will generate a users.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/users for better grouping and structure:

ng g s users

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

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

@Injectable()
export class UsersService {

public API = '//localhost:8080';
public USERS_API = this.API + '/users';

constructor(public http: HttpClient, private authService:
AuthService) {
}

getByScreenName(screenName): Observable<any> {
const apiLink = this.USERS_API + '/' + screenName;
let headers = new HttpHeaders().set('Authorization', 'Bearer
'+this.authService.getToken());
return this.http.get(apiLink, {headers: headers});
}

follow(userId): Observable<any> {
const apiLink = this.USERS_API + '/' + userId + '/follow';
let headers = new HttpHeaders().set('Authorization', 'Bearer
'+this.authService.getToken());
return this.http.put(apiLink, {}, {headers: headers});
}
}

UsersService will use HttpClient to retrieve the user by screenName, follow a user, and so on, using the backend API with the standard REST GET and PUT methods. 

These two services need to be registered as providers in /src/app/app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { TweetsService } from './shared/tweets/tweets.service';
import { UsersService } from './shared/users/users.service';
...

@NgModule({
...
providers: [TweetsService, UsersService, ...],
bootstrap: [AppComponent]
})
export class AppModule { }
..................Content has been hidden....................

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