קריאת Get באנגולר, והבסיס לקריאות http
כדי להשתמש ברכיב http של אנגולר, צריך קודם כל לייבא אותו ולהגדיר אותו בקובץ app.module.ts
import { HttpModule } from '@angular/http';
...
...
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot(appRoutes)
],
שלב נוסף – הוא בתוך ה- service, להזריק אותו אל הקונסטרטור (וכמובן לייבא אותו ).
(במידה וזה service חדש שעכשיו נוצר, אז כמובן לייבא אותו ב–app.module.ts, ולהכניס אותו למערך ה- providers ).
ואז ב- service, נשתמש במודול http כדי לבצע קריאה, ולמפות את התוצאות ל-json.
כדי למפות את התוצאות צריך לייבא חלק של rxjs, שנקרא map.
התוצאה הסופית נראית כך :
---- The Service file -----
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class Get2Service {
apiUrl:string = 'https://jsonplaceholder.typicode.com/users';
constructor(public http:Http) { }
getUsers(){
return this.http.get(this.apiUrl)
.map(response => response.json());
}
}
----- The component file ----------
import { Component, OnInit } from '@angular/core';
import { Get2Service } from './../../services/get2.service';
@Component({
selector: 'app-useget2',
template: `
<h1>list of users</h1>
<div *ngFor="let user of users">
<ul>
<li>{{user.name}}</li>
<li>{{user.email}}</li>
<li>{{user.id}}</li>
</ul>
<hr>
</div>
`
})
export class Useget2Component implements OnInit {
users:any[];
constructor( public getService:Get2Service ) {
this.getService.getUsers().subscribe(users => {
//console.log(users);
this.users = users;
})
}
ngOnInit() {
}
}
קריאת POST באנגולר
בדוגמא הבאה, לקחתי את הדוגמא הקודמת והוספתי לה
- ב- service התווספה פונקציה שנקראת addUser ומבצעת קריאת POST.
- ב-component התווסף טופס להוספת יוזרים, שממופה עם ngModel אל רשימת היוזרים, ואל משתנה חדש בשם יוזר ( אובייקט עם 3 מאפיינים).
- לטופס יש פונקציה שמטפלת ב-submit שלו, שמבצעת גם קריאה ל-service.
---------- The Service File ------------------
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class Get2Service {
apiUrl:string = 'https://jsonplaceholder.typicode.com/users';
constructor(public http:Http) { }
getUsers(){
return this.http.get(this.apiUrl)
.map(response => response.json());
}
addUser(user) {
return this.http.post(this.apiUrl,user).map(response => response.json());
}
}
--------------- The component file -------------
import { Component, OnInit } from '@angular/core';
import { Get2Service } from './../../services/get2.service';
@Component({
selector: 'app-useget2',
template: `
<h1>list of users</h1>
<form (submit)="onSubmit()">
<div class="form-group">
<label>Name:</label>
<input type="text" name="name" [(ngModel)]="user.name" class="form-control">
</div>
<div class="form-group">
<label>Email:</label>
<input type="text" name="email" [(ngModel)]="user.email" class="form-control">
</div>
<div class="form-group">
<label>Phone:</label>
<input type="text" name="phone" [(ngModel)]="user.phone" class="form-control">
</div>
<input type="submit" value="click to submit" class="btn btn-success">
</form>
<hr>
<div *ngFor="let user of users">
<ul>
<li>{{user.name}}</li>
<li>{{user.email}}</li>
<li>{{user.id}}</li>
</ul>
<hr>
</div>
`
})
export class Useget2Component implements OnInit {
users:any[];
user = {name: '',
email:'',phone:''};
constructor( public getService:Get2Service ) {
this.getService.getUsers().subscribe(users => {
//console.log(users);
this.users = users;
})
}
onSubmit(){
this.getService.addUser(this.user).subscribe(user=> {
console.log(user);
this.users.unshift(user);
});
}
ngOnInit() {
}
}
קריאת Delete + PUT באנגולר
המשך הדוגמא שמובאת למעלה – הוספתי כעת גם קריאות put+delete שמוצמדות לכפתורים Edit/Delete.
(הכפתור edit , מעדכן את המודל, וכיוון שהטופס קשור ל- ngModel אז באופן אוטומטי, הטופס מכיל את תוכן המודל).
----- The Service File --------
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class Get2Service {
apiUrl:string = 'https://jsonplaceholder.typicode.com/users';
constructor(public http:Http) { }
getUsers(){
return this.http.get(this.apiUrl)
.map(response => response.json());
}
addUser(user) {
return this.http.post(this.apiUrl,user).map(response => response.json());
}
deleteUser(id) {
return this.http.delete(this.apiUrl + "/" + id).map(response => response.json());
}
updateUser(user) {
return this.http.put(this.apiUrl + '/' + user.id,user).map(response => response.json());
}
}
---- The Component file -----------
import { Component, OnInit } from '@angular/core';
import { Get2Service } from './../../services/get2.service';
@Component({
selector: 'app-useget2',
template: `
<h1>list of users</h1>
<form (submit)="onSubmit(isEdit)">
<div class="form-group">
<label>Name:</label>
<input type="text" name="name" [(ngModel)]="user.name" class="form-control">
</div>
<div class="form-group">
<label>Email:</label>
<input type="text" name="email" [(ngModel)]="user.email" class="form-control">
</div>
<div class="form-group">
<label>Phone:</label>
<input type="text" name="phone" [(ngModel)]="user.phone" class="form-control">
</div>
<input type="submit" value="click to submit" class="btn btn-success">
</form>
<hr>
<div *ngFor="let user of users">
<ul>
<li>{{user.name}}</li>
<li>{{user.email}}</li>
<li>{{user.id}}</li>
</ul>
<br>
<button (click)="onDeleteClick(user.id)" class="button btn-danger btn-sm">Delete</button>
<button (click)="onEditClick(user) " class="button btn-primary btn-sm">Edit</button>
<hr>
</div>
`
})
export class Useget2Component implements OnInit {
users:any[];
user = {name: '',
email:'',phone:''};
isEdit:boolean = false;
constructor( public getService:Get2Service ) {
this.getService.getUsers().subscribe(users => {
//console.log(users);
this.users = users;
})
}
onSubmit(isEdit){
if (isEdit) {
this.getService.updateUser(this.user).subscribe(user=> {
console.log(user);
for(let i = 0; i< this.users.length ; i++ ){
if (this.users[i].id == user.id) {
this.users.splice(i,1);
}
}
this.users.unshift(user);
});
} else {
this.getService.addUser(this.user).subscribe(user=> {
console.log(user);
this.users.unshift(user);
});
}
}
ngOnInit() {
}
onDeleteClick(id) {
console.log(id);
this.getService.deleteUser(id).subscribe(response=> {
console.log(response);
for(let i = 0;i< this.users.length; i++) {
if(this.users[i].id == id) {
this.users.splice(i,1);
}
}
});
}
onEditClick(user) {
this.isEdit = true;
this.user = user;
}
}