【Angular4】如何使用observer-subscribe

一、订阅

Angular4里面有一个非常重要的方法,叫订阅(subscribe);首先看一个例子:

    getStudyTime(userId){
        this.trainService.findStudyTime(userId)
            .subscribe(result=>{
                this.trainList=result;
            })
    }

这里,我们定义了一个方法:getStudyTime(),就是获取学习时间;
按照正常来说,this.trainService.findStudyTime(userId);即可,但是为甚么要用个subscribe()方法呢?是否是多此一举?

二、源代码

    /**
     * Registers handlers for handling emitted values, error and completions from the observable, and
     *  executes the observable's subscriber function, which will take action to set up the underlying data stream
     * @method subscribe
     * @param {PartialObserver|Function} observerOrNext (optional) either an observer defining all functions to be called,
     *  or the first of three possible handlers, which is the handler for each value emitted from the observable.
     * @param {Function} error (optional) a handler for a terminal event resulting from an error. If no error handler is provided,
     *  the error will be thrown as unhandled
     * @param {Function} complete (optional) a handler for a terminal event resulting from successful completion.
     * @return {ISubscription} a subscription reference to the registered handlers
     */
    subscribe(): Subscription;
    subscribe(observer: PartialObserver<T>): Subscription;
    subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;
    protected _trySubscribe(sink: Subscriber<T>): TeardownLogic;

三、翻译

注册处理程序处理从observable发送过来的值,错误和完成情况,并且执行observable的说明功能,这个功能可以设置基础的数据流;

@method subscribe 方法名:subscribe;
@param {局部观察者|功能} observerOrNext(操作)或者一个观察者(observer )定义所有调用的功能;
什么是观察者?前台方法要带着参数,穿过前台时,要穿过一个观察者的瞭望台,穿过这层瞭望台,才能到达后台,根据@GET("/api/v1/train/getTime") 路由来找到对应的方法;这个壁垒,就是观察者的瞭望台(里面有观察者observer);观察者调用观察方法:Observable<any>来调用,监控方法和数据;这里有三个处理器:

  1. error错误处理器:如果出现了错误(error),并且没有错误(error)处理器来处理这个错误,那么这个是为了保障最终时间的结果能够正确的返回;

  2. complete完成处理器:如果最终结果顺利完成;

  3. subscription订阅处理器:返回一个根据注册处理器而获得的描述;

四、格式介绍:

①subscribe(): Subscription;表示subscribe(),方法返回值是属于Subscribe类;
②subscribe(observer: PartialObserver): Subscription;传入参数为观察者,观察者的类型是:PartialObserver泛型;subscrible是Subscription类型的;
③subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;传入值是next,进行判断;是否有下一个值;如果有值,且值为T,则不返回;如果是报错状态(error),则不返回;如果是完成状态(complete),也不返回;
④protected _trySubscribe(sink: Subscriber): TeardownLogic;这个不太了解;

回到我们的例子:

    getStudyTime(userId){
        this.trainService.findStudyTime(userId)
            .subscribe(result=>{
                this.trainList=result;
                loading.dismiss();
            })
    }

如果返回值result是正常的,有值的,那么就进入下一个方法:

				this.trainList=result;

把result赋值给this.trainList;

下面是一个瞭望塔方法,这是我自己打的比方,从前台到后台经过的堡垒,用来观测数据,方法是否正常;就先丧失围城:查看进来或出去的人是否是:

  • 僵尸:error;
  • 正常人:complete;
  • 待定:subscribe;

瞭望塔一般在service.ts文件里面;服务层一般都是夹气包,两边受气;比如后台的service,上面是controller层,congtroller层是前台数据的入口,也是后台数据的出口;service的底层是mapper层,下面连接的是数据库,负责传递从数据库查询得来的数据;果然是服务行业;

    /*warn 获取学习时间*/
    findStudyTime(userId:number):Observable<any>{
        return this.getTimeStudy(userId)
            .map(response=>{
                return response.data || [];
            });
    }
    @GET("/api/v1/train/getTime")
    getTimeStudy(@Query('userId')userId):Observable<any>{
        return null;
    }

五、综述

综上所述,subscribe还是很好的,能够配合瞭望塔处理数据;瞭望塔把后台传来的数据进行分类(3类),然后交给subscribe来处理,

有点类似Java中的Try-catch

;还是很有用处的;

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

陶洲川

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

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

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

打赏作者

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

抵扣说明:

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

余额充值