加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

typescript – Observable.interval问题 – 数据未在模板中更新,

发布时间:2020-12-17 17:15:59 所属栏目:安全 来源:网络整理
导读:在我不断努力教自己Angular2(下次度假时我正在度假!)我有一个问题…我有一个servive,它从我创建的一个虚假的REST服务中提取用户数据.在我的服务中,我希望轮询数据(在这种情况下,我模仿在线的朋友和不在线的朋友).这是带有轮询代码的服务: @Injectable()exp
在我不断努力教自己Angular2(下次度假时我正在度假!)我有一个问题…我有一个servive,它从我创建的一个虚假的REST服务中提取用户数据.在我的服务中,我希望轮询数据(在这种情况下,我模仿在线的朋友和不在线的朋友).这是带有轮询代码的服务:

@Injectable()
export class UserDataService {

    public loginInUser: Subject<UserStatus> = new BehaviorSubject<UserStatus>(null);
    public currentUser: UserStatus;
    public onlineContacts: Subject<UserContact> = new BehaviorSubject<UserContact>(null);
    public userContacts: Subject<UserContact> = new BehaviorSubject<UserContact>(null);

    constructor(public http:Http) {
        this.loadUserStatus(); // this is lower in the Component... I have not included it here
        this.pollContacts();
    }

    private pollContacts() : any {

        var headers = new Headers();
        headers.append('Content-Type','application/json');

        return Observable.interval(30000)
            .switchMap(() => this.http.get('/restservice/contacts',{headers: headers}))
            //.startWith() - Would this allow me to kick off the service when the Component is loaded / called?
            .subscribe((data: any) => {
                data = data.json();
                this.onlineContacts.next(data.onlineContacts);
                this.userContacts.next(data.allContacts);
            });

    }

这是调用服务的组件:

@Component({
    selector: 'contacts-list',directives: [...ROUTER_DIRECTIVES],template: require('./contact-list.html')
})

export class ContactsList {

    public onlineContacts: any;
    public userContacts: any;

    constructor (public userDataService: UserDataService) {
        this.userDataService.onlineContacts.subscribe(
            (onlineContacts) => {
                this.onlineContacts = onlineContacts;
            });

        this.userDataService.userContacts.subscribe(
            (userContacts) => {
                this.userContacts = userContacts;
            });
    }
}

这是我的组件的HTML视图/模板…

<h3>Online Contacts</h3>
<div class="online-contact" *ngIf="onlineContacts?.length > 0" *ngFor="#con of onlineContacts" [routerLink]="['ForeignProfile',{id: con.persId}]">
    <img [src]="con.imgUrl" class="img-circle online-contact-img">
    {{ con.name }}
</div>

<h3>Contacts</h3>
<div class="online-contact" *ngIf="userContacts?.length > 0" *ngFor="#con of userContacts" [routerLink]="['ForeignProfile',{id: con.persId}]">
    <img [src]="con.imgUrl" class="img-circle offline-contact-img">
    {{ con.name }}
</div>

现在我心烦意乱……

>首先,我需要在加载Component / view时启动pollContacts()方法,而不是等待间隔通过.我尝试添加.startWith方法(请参阅注释),但我不确定传递给方法的参数?
>轮询工作和正确的信息从服务传递到组件…但是模板没有更新?我是否需要将异步管道添加到模板中(我确实试过这个并且它不起作用)?
>由于某种原因,两个ngFor指令迭代(或循环)比对象数组的实际长度多一个.例如,当对象数组只包含一个项目且* ngFor =“#conta of userContacts”具有20行(循环20次)时,* ngFor =“#Contats在线接触”有两行(循环两次) userContacts的长度是19!

我意识到自己已经并且一直在就这个问题提出很多问题,但我没有人就此问题进行讨论,所以请容忍我的问题.提前致谢.

解决方法

关于你的第一个问题,是的,你可以使用startWith运算符但必须在switchMap之前使用它:

return Observable.interval(3000)
        .startWith('')
        .switchMap(() => this.http.get('./app/restservice/contacts',{headers: headers}))
        .subscribe((data: any) => {
        });

关于异步,这取决于你.您可以直接使用订阅方法,也可以让管道在引擎盖下使用它.

@Component({
  template: `
    <h3>Contacts</h3>
    <div class="online-contact" *ngFor="#con of userContacts | async">
      <img [src]="con.imgUrl" class="img-circle offline-contact-img">
      {{ con.name }}
    </div>
  `
})
export class ContactsList {
  public onlineContacts: any;
  public userContacts: any;

  constructor (public userDataService: UserDataService) {
    this.userContacts = this.userDataService.userContacts;
  }
}

关于最后一点,我从BehaviorSubjects显示数据没有问题.也许在您的数据级别存在问题.你收到这样的东西了吗?

{
  "allContacts": [
    {
      "name": "Sparky","imgUrl": "https://restlet.com/static/app/img/sparky_right.png"
    }
  ],"onlineContacts": [
    {
      "name": "Sparky","imgUrl": "https://restlet.com/static/app/img/sparky_right.png"
    }
  ]
}

这是一个工作的plunkr:https://plnkr.co/edit/vYQPePG4KDoktPoGaxYu?p=preview.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读