填充可观察的流

时间:2017-01-08 12:35:18

标签: angular rxjs

使用Observable,我想用连接用户填充一个流。

在一本书中,我读了一个非常类似于下面代码的例子:

import {Injectable} from '@angular/core';
import {Subject, BehaviorSubject, Observable} from 'rxjs';
import {User} from "./user";
import {IUserService} from "./IUserService";

let initialConnectedUsers: User[] = [];
interface IUsersOperation extends Function {
    (users: User[]): User[];
}

@Injectable()
export class UserService implements IUserService{
    currentUser: Subject<User> = new BehaviorSubject<User>(null);

    newUser: Subject<User> = new Subject<User>();
    connectedUsers: Observable<User[]>;

    updates: Subject<any> = new Subject<any>();
    create: Subject<User> = new Subject<User>();

    constructor(){
        this.connectedUsers = this.updates
            .scan((users: User[], operation: IUsersOperation) => {
                    return operation(users);
                },
                initialConnectedUsers)
            .publishReplay(1)
            .refCount();

        this.create.map(function (user: User): IUsersOperation {
            return (users: User[]) => {
                console.log('foo');
                return users.concat(user);
            }
        }).subscribe(this.updates);

        this.newUser.subscribe(this.create);
    }

    public setCurrentUser(newUser: User): void {
        this.currentUser.next(newUser);
        this.newUser.next(newUser);
    }
}

export var userServiceInjectables: Array<any> = [
    UserService
];

但在我的情况下,Observable“create”不使用,我看不到控制台日志。

1 个答案:

答案 0 :(得分:0)

在应用程序初始化时(例如:app.component.ts)我写了这段代码:

this.userService.connectedUsers.subscribe(() => ({}));