从一个可观察的内部返回

时间:2017-11-15 03:56:23

标签: javascript angular typescript

我认为从根本上说我做错了什么。我试图通过从过滤列表中提取单个实体来找到它,如果没有实体,我需要创建一个实体。

我觉得这个函数错了,因为我应该返回一个observable而不是什么都不返回

getOrCreateNew(receiverId: number) : Observable<Conversation> {
    var userId = this.identity.userInfo.id;

    //TODO: you should be using an expression here, and having a builder for generating your
    //filters in case you want to switch them in the future
    var employerFilter = new PropertyFilterNode("EmployerUserId", FilterCondition.Equal, receiverId.toString());
    var employeeFilter = new PropertyFilterNode("EmployeeUserId", FilterCondition.Equal, userId.toString());
    let conversationFilter = new BinaryFilterNode(employerFilter, employeeFilter, Combiner.Or);

    this.getList(conversationFilter).subscribe(entities => {
        if (entities == null || entities.length == 0) {
            let conversation: Conversation;
            conversation.employerUserId = receiverId;
            conversation.employeeUserId = userId;
            return this.create(conversation);
        }
        else {
            let entity = entities[0];
            return Observable.of(entity); //.Return(entity)
        }
    });

    return null;
}

如何返回从subscribe内部返回的observable?

2 个答案:

答案 0 :(得分:1)

return放在this.getList之前:

return this.getList(conversationFilter).subscribe(entities => {

答案 1 :(得分:1)

getList订阅的工作方式表明它应该是mergeMapswitchMap(考虑到create也会返回一个observable):

return this.getList(conversationFilter).mergeMap(entities => {
    if (entities == null || entities.length == 0) {
        let conversation: Conversation;
        conversation.employerUserId = receiverId;
        conversation.employeeUserId = userId;
        return this.create(conversation);
    }
    else {
        let entity = entities[0];
        return Observable.of(entity); //.Return(entity)
    }
});

在这种情况下,应该订阅从getOrCreateNew返回的observable,以便发出值,因为它没有在内部订阅。