使用异步管道的Socket.io和Angular

时间:2018-10-22 19:45:13

标签: angular typescript socket.io

我有问题。我发现异步管道需要Observables的许多信息。所以,我以为我从socket.on事件上的服务返回了可观察到的结果,但似乎我错了。我应该如何正确实施呢?

服务:

public getUsers(): Observable<any> {
    return new Observable<any>(observer => {
        this.socket.on('my_users', (data) => observer.next(data));
    });
}

组件:

users: Observable<any[]>;

this.http.getUsers().subscribe((user: any) => {
    this.users = user.data;
});

模板:

<button class="send_to_username" 
        value="{{user}}" 
        *ngFor='let user of users;  let i = index' 
        [ngClass]="{'active':isClicked[i]}"
        (click)="isClicked[i] = (isClicked[i]? false :true); getReceiver(user)"
>{{user | async}}</button>

服务器:

@socketio.on('username', namespace='/private')
def receive_username(username):
users[username] = request.sid
print('Username added!')
print(users)
emit('my_users',
     {'data': list(users.keys())})
  

错误错误:“ InvalidPipeArgument:管道“ AsyncPipe”的“ 111111””

1 个答案:

答案 0 :(得分:0)

您将users声明为Observable。但是它正在初始化为其他数据,即您的数据。

// This part is a subscription to an observable:
this.http.getUsers().subscribe((user: any) => {
    // This part is just a regular assignment:
    this.users = user.data;
});

所以这一行是错误的:users: Observable<any[]>;

相反,它应该类似于:users: Array<any> = []

您的错误实际上是由于其他原因。您使用的异步管道不正确。

<button
    class="send_to_username"
    value="{{user}}"
    *ngFor='let user of users; let i = index'
    [ngClass]="{'active':isClicked[i]}"
    (click)="isClicked[i] = (isClicked[i]? false :true); getReceiver(user)"> 
    {{user | async}}
</button>

应该是:

<button
    class="send_to_username"
    value="{{user}}"
    *ngFor='let user of users; let i = index'
    [ngClass]="{'active':isClicked[i]}"
    (click)="isClicked[i] = (isClicked[i]? false :true); getReceiver(user)"> 
    {{user}}
</button>

但是,如果您希望通过管道传输Observable的输出,则可以删除所有这些内容:

users: Observable<any[]>;

this.http.getUsers().subscribe((user: any) => {
    this.users = user.data;
});

而只需写:

<button
    class="send_to_username"
    value="{{user}}"
    *ngFor='let user of (http.getUsers() | async); let i = index'
    [ngClass]="{'active':isClicked[i]}"
    (click)="isClicked[i] = (isClicked[i]? false :true); getReceiver(user)"> 
    {{user}}
</button>