2017-01-08 102 views
-1

使用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 
]; 

但在我的情況下,可觀察到「創造」不用,我沒有看到控制檯日誌。

+0

是什麼*「在我的情況下,可觀察到‘創造’不使用」 *是什麼意思? – martin

+0

你可以在這裏閱讀(https://github.com/ng-book/angular2-rxjs-chat/blob/master/app/ts/services/MessagesService.ts)代碼是什麼啓發了我。在那個代碼中,connectedUsers的等價物被填充了observables創建和更新 – mickaelw

回答

0

在應用程序的初始化(用於爲例:app.component.ts)我寫這篇文章的代碼:

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