import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { SharedModule } from '../shared/shared.module';
import { UserService } from './user.service';
@NgModule({
imports: [
CommonModule,
HttpClientModule,
SharedModule
],
declarations: [],
providers: [UserService]
})
export class CoreModule {}
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({providedIn: 'root'})
export class UserService {
constructor(private http: HttpClient) { }
test() {
let data: Observable<Object> = this.http.get('users/1');
data.subscribe(result => console.log(result));
}
}
Implementing a Service in a Component
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { UserService } from '../core/user.service';
import { User } from '../core/user.model';
import { HttpErrorResponse } from '@angular/common/http';
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
users: User[];
constructor(private userService: UserService) {}
ngOnInit() {
this.userService
.getUsers()
.subscribe(
(users: User[]) => this.users = users,
(error: HttpErrorResponse) => console.log(error)
);
}
}
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from './user.model';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http: HttpClient) {}
getUser(id: number): Observable<User> {
return this.http.get<User>(`/users/${id}`);
}
getUsers(): Observable<User[]> {
return this.http.get<User[]>('/users');
}
createUser(user: User): Observable<User> {
return this.http.post<User>('/users', user);
}
updateUser(user: User): Observable<User> {
return this.http.put<User>(`/users/${user.id}`, user);
}
deleteUser(user: User): Observable<User> {
return this.http.delete<User>(`/users/${user.id}`);
}
}