rebirth http
v6.0.2
類似 Java JPA 的 Angular HTTP 用戶端。
$ npm install @ng-zorro/rebirth-http --save
RebirthHttpModule
import { RebirthHttpModule } from '@ng-zorro/rebirth-http' ;
@ NgModule ( {
imports : [ BrowserModule , RebirthHttpModule ] ,
declarations : [ AppComponent ] ,
bootstrap : [ AppComponent ] ,
} )
export class AppModule { }
import {
Any ,
RebirthHttpClient ,
JSONP ,
GET ,
POST ,
PUT ,
DELETE ,
PATCH ,
BaseUrl ,
Query ,
Path ,
Body ,
} from 'rebirth-http' ;
import { Observable } from 'rxjs/Observable' ;
import { HttpClient } from '@angular/common/http' ;
@ Injectable ( )
export class ArticleService extends RebirthHttpClient {
constructor ( http : HttpClient ) {
super ( http ) ;
}
@ GET ( 'article' )
getArticles (
@ Query ( 'pageIndex' ) pageIndex = 1 ,
@ Query ( 'pageSize' ) pageSize = 10
) : Observable < SearchResult < Article > > {
return Any ; // return Any as a placeholder
}
@ GET ( 'article/:id' )
getArticleByUrl ( @ Path ( 'id' ) articleUrl : string ) : Observable < Article > {
return Any ;
}
@ POST ( 'article' )
createArticle ( @ Body article : Article ) : Observable {
return Any ;
}
@ PUT ( 'article/:id' )
updateArticle (
@ Path ( 'id' ) id : string ,
@ Body article : Article
) : Observable < Article > {
return Any ;
}
@ DELETE ( 'article/:id' )
deleteArticleById ( @ Path ( 'id' ) id : string ) : Observable < Article > {
return Any ;
}
@ JSONP ( 'article/:id' )
getArticleByJsonp (
@ Path ( 'id' ) id : string ,
@ Query ( 'name' ) name : string
) : Observable < Article > {
return Any ;
}
@ POST ( 'file/upload' )
upload ( @ Body formData : FormData ) : Observable < any > {
return Any ;
}
}
ArticleService
現在您可以呼叫ArticleService
的方法來觸發 HTTP 請求! :)
您可以為任何RebirthHttpClient
新增攔截器。
import { config } from '@/config' ;
import { RebirthHttpProvider } from '@ng-zorro/rebirth-http' ;
@ Component ( {
selector : 'app-root' ,
} )
export class AppComponent {
constructor ( rebirthHttpProvider : RebirthHttpProvider ) {
rebirthHttpProvider . baseUrl ( config . api . host ) . addInterceptor ( {
request : ( request ) =>
console . log ( 'Global interceptors(request)' , request ) ,
response : ( response ) =>
console . log ( 'Global interceptors(response)' , response ) ,
} ) ;
}
}
RebirthHttpClient
每個負責 HTTP 的服務都應該繼承RebirthHttpClient
。
getBaseUrl(): string
: 傳回 RebirthHttp 用戶端的基本 urlgetDefaultHeaders(): { [name: string]: string }
:以鍵值對形式傳回 RebirthHttp 的預設標頭這些裝飾器應該用在繼承RebirthHttpClient
的類別上。
@BaseUrl(url: string)
:更改 RebirthHttpClient 的基本 url@DefaultHeaders(headers: Object)
:更改 RebirthHttpClient 的預設標頭這些裝飾器將使RebirthHttpClient
的方法能夠發送 HTTP 請求。
@GET(url: string)
@POST(url: string)
@PUT(url: string)
@DELETE(url: string)
@JSONP(url: string)
@PATCH(url: string)
@HEAD(url: string)
@OPTIONS(url: String)
您可以使用下面的裝飾器來修改 HTTP 選項。
@Headers(headers: any)
@RequestOptions(headers: any)
@Extra(headers: any)
使用下面的裝飾器來裝飾RebirthHttpClient
方法的參數,使參數成為對應的 HTTP 選項。
@Path(key: string)
@Query(key: string)
@Header(key: string)
@Body
感謝Paldom/angular2-rest給我們的靈感。
麻省理工學院