Angular 进阶之二: ngx-resource

Git 地址

          GitHub - troyanskiy/ngx-resource: Resource (REST) Client for Angular 2

官方介绍

          Resource Core 是 ngx-resource lib的演变,它为开发人员提供了灵活性。 每个开发人员都可  以实现自己的请求处理程序以轻松自定义行为。 事实上,@ngx-resource/core 是一个抽象的公共库,它使用 ResourceHandler 发出请求,因此甚至可以将 node.js 服务器端的 lib 与 typescript 一起使用。 你只需要为它实现一个 ResourceHandler 。

安装

      npm i --save @ngx-resource/core @ngx-resource/handler-ngx-http

使用

一、创建Resource class

说明

例子中涉及到的API介绍

1在IResourceParams中可以指定请求路径前缀

@ResourceParams({
    pathPrefix: '/api'
})

2: 在IResourceAction中指定路径,请求方式,返回类型等

// will make an post request to /api/login
  @ResourceAction({
    method: ResourceRequestMethod.Post,
    path: '/login',
    returnAs: ResourceActionReturnType.Promise
  })
  login: IResourceMethodPromise<{login: string, password: string}, IReturnData>;

3请求方式有七种,根及实际情况选择,默认值是Get

export declare enum ResourceRequestMethod {
Get = 1,
Post = 2,
Put = 3,
Delete = 4,
Options = 5,
Head = 6,
Patch = 7

4: 返回类型有三种

export declare enum ResourceActionReturnType {
Promise = "promise",
Observable = "observable",
Resource = "resource"

例子以从天气网获取北京天气为例

import { Injectable } from '@angular/core';
import { Resource,
  ResourceParams,
  ResourceAction,
  ResourceRequestMethod,
  IResourceMethodPromise,
  ResourceActionReturnType,
  IResourceMethodObservable,
  ResourceHandler,
  IResourceMethodPromiseStrict
} from '@ngx-resource/core';
import { IWeather } from './weather';

@Injectable()
@ResourceParams({
  url: 'http://wthrcdn.etouch.cn/weather_mini?citykey=101010100'
  // url: 'http://wthrcdn.etouch.cn/weather_mini' Use when there are parameters
})
export class DataResource extends Resource {
  @ResourceAction({
    method: ResourceRequestMethod.Get,
    returnAs: ResourceActionReturnType.Promise
  })
  getWeather: IResourceMethodPromise<{}, IWeather>;

  @ResourceAction({
    method: ResourceRequestMethod.Get,
    returnAs: ResourceActionReturnType.Observable
  })
  getWeatherObservable: IResourceMethodObservable<{}, IWeather>;

  @ResourceAction({
    method: ResourceRequestMethod.Get,
    // params: { citykey: 101010100 }, Works but not recommended
    returnAs: ResourceActionReturnType.Promise
  })
  getWeatherByParams: IResourceMethodPromiseStrict<null, null, {citykey: number}, IWeather>;

  constructor(restHandler: ResourceHandler ) {
    super(restHandler);
  }
}

二、app Module

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { ResourceModule, ResourceHandlerHttpClient } from '@ngx-resource/handler-ngx-http';

import { AppComponent } from './app.component';
import { DataResource } from './weather/dataResource.service';
import { MyAuthResource } from './login/authResource.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    ResourceModule.forRoot()
  ],
  providers: [
    ResourceHandlerHttpClient,
    DataResource,
    MyAuthResource
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

三、使用

           

下面列举了不同种返回结果的处理方式

import { Component, OnInit } from '@angular/core';
import { DataResource } from './weather/dataResource.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'blogDemo';

  weather = {
    data: { city: '' }
  };

  constructor(private dataResource: DataResource) {
  }

  async ngOnInit(): Promise<void> {

    // use #1
    this.dataResource.getWeather().then(weather => {
      this.weather = weather;
    });
    // use #2
    this.weather = await this.dataResource.getWeather();

    // use #3
    this.weather = await this.dataResource.getWeatherObservable().toPromise();

    // use #4
    this.dataResource.getWeatherObservable()
      .subscribe(
        (res: any) => {
            this.weather = res;
        },
        (err: any) => {
            console.error(err);
        }
     );

    // use #5
    this.weather = await this.dataResource.getWeatherByParams(null, null, { citykey: 101010100 });

    console.log('this.weather', this.weather);
  }

}

四、运行结果

五、post请求

1. 创建Resource class具体路径以实际情况为准

import { Injectable } from '@angular/core';
import { Resource,
  ResourceParams,
  ResourceAction,
  ResourceRequestMethod,
  ResourceHandler,
  IResourceMethodPromise
} from '@ngx-resource/core';
import { IReturnData } from './auth';

@Injectable()
@ResourceParams({
  pathPrefix: '/api'
})
export class MyAuthResource extends Resource {

  // will make an post request to /api/login
  @ResourceAction({
    method: ResourceRequestMethod.Post,
    path: '/login'
  })
  login: IResourceMethodPromise<{login: string, password: string}, IReturnData>;

  constructor(restHandler: ResourceHandler ) {
    super(restHandler);
  }
}

2. models

export interface IReturnData {
  code?: number;
  message?: number;
}

3. 使用

// use #6
    await this.authResource.login({login: 'test', password: 'test'});

Demo

1: 执行npm i

2: 执行 ng serve --open

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值