Angular Observables vs Promise CRUD和刷新数据

时间:2017-05-23 16:54:02

标签: angular angular-services

对于简单的crud应用,我有几个关于角2/4模式的问题。我查看过的大多数示例,在插入/更新等后都没有看到数据是如何刷新的。

我对Observables有点新意,但在插入/更新/删除后刷新数据的例外情况下了解大多数模式。有人可以解释刷新数据的最佳方法吗?我真的需要使用Observables而不是promises吗?是否接受仍然使用承诺?

如何使用Observables执行以下操作?

users.service

insertPromise(user : User)
{
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    let url = this.baseUrl;

    return this.http.post(url, JSON.stringify(user),options)          
          .do(data=>console.log(JSON.stringify(data))) 
          .toPromise()
          .then(this.extractPromiseData)          
          .catch(this.handleError);
}

insertObservable(user : User) {

    this.usersService.insert(user)
      .subscribe(
      resp => {

        console.log(resp);
      },
      error => this.errorMessage = <any>error);
  }

user-list.component (插入后包含刷新)

insert(user: User)
{
     this.usersService.insertPromise(user)
         .then(result=>console.log(result))
         .then(
           ()=>this.usersService.getAllUsers()
           .then(
             users=>

             this.users = users

             )
           .catch(error=>console.log(error))           
           )
         .catch(error=>console.log(error));
}

insertObservable(user: User)
  {

    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    let url = this.baseUrl;

     return this.http.post(url, JSON.stringify(user),options)
          .map((response: Response) => response.json())
          .do(data=>console.log(JSON.stringify(data)))  
          .catch(this.handleError);
  }

1 个答案:

答案 0 :(得分:0)

这取决于您的实施。例如,您可以返回新用户以响应POST请求,然后将此用户数据放入this.users。另一个选择是在成功POST / PUT之后重新加载整个列表。我认为第一种方法更好,因为它不会导致任何额外的HTTP请求。代码示例:

insert(user: User) {
  const headers = new Headers({ 'Content-Type': 'application/json' });
  const options = new RequestOptions({ headers: headers });
  const url = this.baseUrl;

  return this.http.post(url, JSON.stringify(user), options)          
    .do(response => console.log(JSON.stringify(data))) 
    // first, convert HTTP response to User instance (easier if User is
    // just an interface, harder if it’s a class)
    .map(response => response.json().user as User)
    // then, push that User object to the existing array of users
    // then you don’t have to “refresh” this.users, because it’s already
    // up to date
    .map(user => this.users.push(user))
    .catch(this.handleError);
}
相关问题