Angular 003 依赖注入自定义服务实现异步处理

2 篇文章 0 订阅
1 篇文章 0 订阅

Angular 003 组件注入自定义服务-实现异步处理

服务AsyncService,用timeout来模拟异包装异步方法

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AsyncService {

  constructor() { }
// 同步方法
  getData(input:string){
    return input;
  }
// 使用callback的方式接收异步处理结果
  getDataAsyncByCallback(input:string, callback:any, timeout:number=1000) {
    setTimeout(() => {
      var result=`data=${input}, timeout=${timeout}`;

      return callback(result);
    }, timeout);
  }
// 使用Promise接收异步处理结果
  getDataAsyncByPromise(input:string, timeout:number=1000) : Promise<string> {
    var promise = new Promise<string>((resolve) => {
      setTimeout(() => {
        var result:string =`data=${input}, timeout=${timeout}`;
        resolve(result);
      }, timeout);
    });

    return promise;
  }
// 使用Rxjs的Observable接收异步处理结果
  getDataAsyncByRxjs(input:string, timeout:number=1000) : Observable<string> {
    var observable = new Observable<string>((oberver) => {
      setTimeout(() => {
        var result:string =`data=${input}, timeout=${timeout}`;
        oberver.next(result);
        // oberver.error("exception occurred");
      }, timeout);
    });

    return observable;
  }
}

组件AsyncTestComponent注入AsyncService

import { Component, OnInit } from '@angular/core';
import { AsyncService } from '../../../services/async.service'

@Component({
  selector: 'app-async-test',
  templateUrl: './async-test.component.html',
  styleUrls: ['./async-test.component.scss']
})
export class AsyncTestComponent implements OnInit {

// 定义了一些字段在UI看结果
  public synchronousTextIn:string='';
  public synchronousTextOut:string='';

  public asyncCallBackIn:string='';
  public asyncCallBackOut:string='';

  public asyncPromiseIn:string='';
  public asyncPromiseOut:string='';

  public asyncRxjsIn:string='';
  public asyncRxjsOut:string='';

  constructor(private asyncService:AsyncService) { }

  ngOnInit(): void {
  }
// 同步方法
  synchronousGet(){
    this.synchronousTextOut = this.asyncService.getData(this.synchronousTextIn);
  }
// 使用callback的方式接收异步处理结果
  asyncCallBackGet(){
    this.asyncService.getDataAsyncByCallback(this.asyncCallBackIn, (data:string) => {
      this.asyncCallBackOut = data;
    });
  }
// 使用Promise接收异步处理结果
  asyncPromiseGet() {
    var promise = this.asyncService.getDataAsyncByPromise(this.asyncPromiseIn, 2000);

    promise.then((out:string) => {
      this.asyncPromiseOut = out;
    })
  }
// 使用Rxjs的Observable接收异步处理结果
  asyncRxjsGet() {
    var observable = this.asyncService.getDataAsyncByRxjs(this.asyncRxjsIn, 3000);

    observable.subscribe((out:string) => {
      this.asyncRxjsOut = out;
    });
  }
}

// async-test.component.html

<h2>async-test</h2>
<div>
    <span>synchronous</span>
    <button (click)="synchronousGet()">synchronous-get</button>
    <input type="text" [(ngModel)]="synchronousTextIn" placeholder="in">
    <input type="text" [(ngModel)]="synchronousTextOut" placeholder="out" class="text-out" />
</div>

<br>

<div>
    <span>async-callback</span>
    <button (click)="asyncCallBackGet()">async-callback</button>
    <input type="text" [(ngModel)]="asyncCallBackIn" placeholder="in" />
    <input type="text" [(ngModel)]="asyncCallBackOut" placeholder="out" class="text-out" />
</div>

<br>

<div>
    <span>async-promise</span>
    <button (click)="asyncPromiseGet()">async-promise</button>
    <input type="text" [(ngModel)]="asyncPromiseIn" placeholder="in" />
    <input type="text" [(ngModel)]="asyncPromiseOut" placeholder="out" class="text-out" />
</div>

<br>

<div>
    <span>async-rxjs</span>
    <button (click)="asyncRxjsGet()">async-rxjs</button>
    <input type="text" [(ngModel)]="asyncRxjsIn" placeholder="in" />
    <input type="text" [(ngModel)]="asyncRxjsOut" placeholder="out" class="text-out" />
</div>

运行结果

最后福利-AsyncService的单元测试.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Punkerwei

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值