繁体   English   中英

从 Angular2 服务返回一个空的 Observable

[英]Return an empty Observable from an Angular2 Service

我正在构建一个 Angular 2 应用程序,它使用一项服务来收集数据。 该服务确实包含以下逻辑:

/* ========== CORE COMPONENTS ========== */
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

/* ========== MODELS ========== */
import { IApplicationViewModel } from './models/application.model';

/* ========== CONSTANTS ========== */
import { LogzillaServerConfiguration } from '../../app.configuration';

@Injectable()
export class ApplicationService {
    private getAllEndpoint = LogzillaServerConfiguration.host + '/api/administration/application/getAll';

    // Initializes a new instance of the 'ApplicationService'.
    constructor(private http: Http) { }

    // Get all the 'logzilla' applications.
    getApplications(): Observable<IApplicationViewModel[]> {
        return this.http.get(this.getAllEndpoint)
            .map((response: Response) => <IApplicationViewModel[]>response.json().model)
            .catch(this.handleError);
    }

    // Handle an error that occured while retrieving the data.
    // This method will throw an error to the calling code.
    private handleError(error: Response) {
        return Observable.empty();
    }
}

该服务所做的是从端点检索数据,并将其映射到模型,当发生错误时,我返回一个空的Observable

我还有一个解析器,用于在更改活动路由之前从服务加载数据。 此解析器确实包含以下逻辑:

/* ========== CORE COMPONENTS ========== */
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';

/* ========== APPLICATION SERVICES ========== */
import { ApplicationService } from './application.service';

/* ========== MODELS ========== */
import { IApplicationViewModel } from './models/application.model';
import { IApplicationLogLevel } from './models/applicationLevel.model';

// Defines the 'resolver' which is used to resolve the applications.
@Injectable()
export class ApplicationResolver implements Resolve<IApplicationViewModel[]> {

    // Initializes a new instance of the 'ApplicationResolver'.
constructor(private applicationService: ApplicationService) { }

// Get all the registered applications.
resolve(route: ActivatedRouteSnapshot) {
    return this.applicationService.getApplications();
}
}

我的路线的定义是:

{ path: 'applications', component: ApplicationComponent, pathMatch: 'full', resolve: {
            application: ApplicationResolver
        }},

但是,当我浏览到/applications ,遇到错误Uncaught (in promise): Error: no elements in sequence. .

编辑:添加组件

@Component({
    selector: 'logzilla-applications',
    templateUrl: './src/app/pages/applications/application.template.html'
})
@Injectable()
export class ApplicationComponent implements OnInit {
    hasApplications: boolean;
    applications: IApplicationViewModel[];
    errorMessage: string;

    // Initializes a new instance of the 'ApplicationComponent'.
    constructor (private route: ActivatedRoute) { 
        console.log('I am here.');
    }

    // This method is executed when the component is loaded.
    ngOnInit() { 

    }

我的组件的构造函数不是事件调用。 这怎么解决。

亲切的问候,

Observable.of([])替换Observable.empty() Observable.of([]) 的亲景ofempty是什么官方角度英雄之旅教程使用返回一个空观察到的,是我一直在用我所有的应用程序是什么。

它们之间的区别似乎是返回任何内容,还是空数组。

来自官方rxjs文档:

Observable.empty()

创建一个Observable,它不会向Observer发送任何项目,并立即发出完整的通知。

Observable.of()

创建一个Observable,它会一个接一个地发出您指定为参数的某些值,然后发出完整的通知。

解析器尝试订阅给定的Observable并将Observable序列的第一个结果传递给组件(实际上是ActivatedRoute对象)。

但是因为你的Observable在发出结果之前触发了已完成的事件,所以解析器不会得到结果。 这就是你的错误来自哪里。

您必须返回Observable.of(null)Observable.of([])或类似的东西。 然后,您可以处理组件中的空输入。

页面包含有关Observable.empty()函数的更多信息。

您可以使用此返回空的 observable -

return new Observable<HttpEvent<any>>();

你也可以使用类型来摆脱类型脚本错误。

暂无
暂无

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

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