简体   繁体   English

Angular2无法从模拟服务返回项目

[英]Angular2 unable to return items from the mock service

Hi I am writing unit test cases for Angular5 application. 嗨,我正在为Angular5应用程序编写单元测试用例。 I am calling one function loadscopesdata() as below. 我正在调用一个函数loadscopesdata(),如下所示。

loadScopesData() {
        this.scopeService.getScopesByTenantId(this._searchText, this._onlyActive).subscribe(results => this.onScopesDataLoadSuccessful(results), error => this.onScopesDataLoadFailed(error));
    }

Which calls below service. 下面哪个叫服务。

getScopesByTenantEndpoint<T>(searchText: string, onlyActive: boolean): Observable<T> {
        var scopes = localStorage.getItem('scopeObject');
        if (scopes) {
            return Observable.create(scopes);
        }
        else {
            return Observable.empty();
        }
    }

Whenever above code executed, It always returns control into onScopesDataLoadFailed. 每当执行以上代码时,它始终将控制权返回到onScopesDataLoadFailed。 Can someone help me to figure it out? 有人可以帮我弄清楚吗? Thank you. 谢谢。

afaik Observable.create is mostly used to tell how the value will be passed to the subscriber, you already have your value and don't want to process somethig special, so can you try to simply use return Observable.of(scopes) instead. afaik Observable.create通常用于告诉值如何传递给订阅者,您已经拥有了值,并且不想处理特殊的东西,因此您可以尝试简单地使用return Observable.of(scopes)代替。

[With Observable.create()] [使用Observable.create()]

getScopesByTenantEndpoint<T>(searchText: string, onlyActive: boolean): Observable<T> {
    return Observable.create(observer=>{
        const scopes = localStorage.getItem('scopeObject');

        //If you want to throw an err
        if(!scopes){
            throw 'no scope given'
        }

        observer.next(scopes);
    } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM