Truyền tham số cho webservice trong Angular

Giới thiệu nội dung bài viết

Chào các bạn,hôm nay anh sẽ hướng dẫn mọi người cách gọi Truyền tham số cho webservice bên ngoài ở trong dự án Angular là như thế nào nhé.

1. Truyền param trên URL

Khi mình gọi webservice bên ngoài, thì có nhiều webservice yêu cầu mình thêm dữ liệu trong body để truyền lên cho webservice. Để làm được việc này ta dùng đối tượng Http Param để truyền thêm giá trị.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable} from 'rxjs/Rx';
 
import { repos} from './repos';
 
@Injectable()
export class GitHubService {
 
   baseURL= "https://api.github.com/";
 
   constructor(private httpClient: HttpClient){
   }
 
   getRepos(userName: string, PageNo: string, SortOn: string): Observable<repos[]> {
 
 
        let params = new HttpParams()
                .set('page', PageNo)
                .set('sort', SortOn);
   
        console.log(params.toString());
 
        return this.httpClient.get<repos[]>(this.baseURL + 'users/' + userName + '/repos', {params});
   }
  
}
  • Chúng ta truyền param như sau:
1
this.httpClient.get<repos[]>(this.baseURL + 'users/' + userName + '/repos', {params})

2. Truyền giá trị trên http header gọi webservice

1
2
3
4
5
getPeopleWithHeaders(): Observable<Person[]> {
    const headers = { 'content-type': 'application/json'}  
    console.log(headers)
    return this.http.get<Person[]>(this.baseURL + 'people',{'headers':headers})
  }

Chúng ta sử dụng tham số withCredentials=true cho request để gửi cookie.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
getReposWithCookies(userName: string): Observable<repos[]> {
 
      const params = new HttpParams()
        .set('sort', "description")
        .set('page',"2");
  
      const headers = new HttpHeaders()
        .set('Content-Type', 'application/json')
        
  
      return this.http.get<repos[]>(this.baseURL + 'users/' + userName + '/repos', { 'params': params, 'headers': headers, withCredentials: true })
        .pipe(
          map((response) => {
            return response;
          }),
          catchError((err, caught) => {
            console.error(err);
            throw err;
          }
          )
        )
    }
 

4. Bắt Errors ở Component

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Trong trường hợp gọi webservice sẽ xảy ra tình trạng  webservice bị lỗi. Thì chúng ta  bắt lại lỗi đó.

public getRepos() {
    this.loading = true;
    this.errorMessage = "";
    this.githubService.getReposCatchError(this.userName)
      .subscribe(
        (response) => {                           //Next callback
          console.log('response received')
          this.repos = response;
        },
        (error) => {                              //Error callback
          console.error('error caught in component')
          this.errorMessage = error;
          this.loading = false;
    
          //throw error;   //You can also throw the error to a global error handler
        }
      )
  }

hàm subscribe cung cấp cho chúng ta 3 tham số callbacks.

1
.subscribe(success, error, completed);

Trong trường hợp lỗi chúng ta sẽ xử lý trong hàm error.

1
2
3
4
5
(error) => {                              //Error callback
          console.error('error caught in component')
          this.errorMessage = error;
          this.loading = false;
        }

5. Bắt Errors ở Service

Ngoài bắt lỗi ở Component chúng ta có thực hiện bắt lỗi ở Service. Chúng ta sử dụng hàm catchError.

1
2
3
4
5
6
7
8
9
10
11
12
13
getRepos(userName: string): Observable<repos[]> {
    return this.http.get<repos[]>(this.baseURL + 'usersY/' + userName + '/repos')
      .pipe(
        catchError((err) => {
          console.log('error caught in service')
          console.error(err);
 
          //Handle the error here
 
          return throwError(err);    //Rethrow it back to component
        })
      )
  }

Mọi người hãy Subscribe kênh youtube dưới đây nhé để cập nhật các video mới nhất về kỹ thuật và kỹ năng mềm

Các khoá học lập trình MIỄN PHÍ tại đây


Comments