Angular2:发送API调用后更新UI

时间:2017-06-30 11:19:54

标签: angular rxjs

我正在使用Angular(2)构建UI,我需要项目详细信息视图来调用API,以便每次用户与UI交互时获取项目的最新数据。 即删除任务或将任务标记为项目完成时(使用API​​调用),应再次调用项目端点以获取最新数据。

我以为我用下面的代码破解了它,但按时间顺序实际发生的是:

  1. 进行了对GET项目调用的OPTIONS调用。
  2. 对项目进行GET调用。
  3. 对任务进行DELETE调用。
  4. 这意味着项目再次加载 BEFORE 更改时应该是项目加载 AFTER 进行更改。

    这是我的project-detail.component.ts的代码:

    public getProject(): void {
        this.route.params
        .switchMap((params: Params) => this.projectService.getProject(+params['id']))
        .subscribe(project => this.project = project);
    
    }    
    
    public deleteTask(task): void {
        this.projectService
            .deleteTask(task, this.project)
            .subscribe(
                this.getProject()
            );
    }
    

    这是project.service.ts的代码:

    public getProject(id: number): Promise<Project> {
        const url = `${this.projectsURL}/${id}`;
    
        return this.http.get(url)
                  .toPromise()
                  .then(response => response.json() as Project)
                  .catch(this.handleError);
    }
    
    public deleteTask(task: Task, project: Project): any {
        const url = `${this.projectsURL}/${project.id}/tasks/${task.id}`;
    
        return this.http.delete(url)
            .toPromise()
            .then(() => task)
            .catch(this.handleError);
    
      }
    

2 个答案:

答案 0 :(得分:0)

project-detail.component.ts中,您应该使用then代替subscribe,因为您要返回Promise而不是Observable

public deleteTask(task): void {
    this.projectService
        .deleteTask(task, this.project)
        .then(() => this.getProject());
}

答案 1 :(得分:0)

我会利用FlatMap运算符:

someMethod(){
    let obs = this.deleteTask(task).subscribe(project => this.project = project);
  }

  public getProject(): void {
    this.route.params
      .switchMap((params: Params) => this.projectService.getProject(+params['id']))
  }

  public deleteTask(task): void {
    this.projectService
      .deleteTask(task, this.project)
      .flatMap(() => {
        return this.getProject();
      }
      );
  }

希望有所帮助。

编辑:

我创建了一个角度2组件,可以实现您想要的行为。

import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { ActivatedRoute } from '@angular/router';
import { forwardRef, Directive, Input, ElementRef, Renderer, OnInit, AfterViewInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.less']
})
export class HomeComponent implements OnInit {
  projectService: ProjectService;
  project: Project;

  constructor(private route: ActivatedRoute,http: Http){
    this.projectService = new ProjectService(http);
  }
  ngOnInit() {
    this.getProject()
      .subscribe(project => {
        console.log(project);
        this.project = project
      });
  }

  public getProject(): Observable<any> {
    return this.route.params
      .flatMap((params) => this.projectService.getProject(+params['id']))
  }

  public delete(){
    this.deleteTask({id:1});
  }
  public deleteTask(task): void {
    this.projectService.deleteTask(task, this.project)
      .flatMap((response: any) => {
        return this.getProject();
      })
      .subscribe((project:Project)=>{
        this.project=project;
    });
  }
}

export class ProjectService {
  projectsURL = "";
  constructor(private http: Http) {

  }
  // public getProject(id: number): Observable<Project> {
  //   const url = `${this.projectsURL}/${id}`;
  //   return this.http.get(url)
  //     .map(response => response.json() as Project)
  // }

  // public deleteTask(task: Task, project: Project): Observable<any> {
  //   const url = `${this.projectsURL}/${project.id}/tasks/${task.id}`;
  //   return this.http.delete(url)
  //     .map(response => response.json())
  // }

  public getProject(id: number): Observable<Project> {
    return Observable.create(observer=>{
      console.log("Get Project");
      observer.next({id:"Project1"})
    }).delay(500);
  }

  public deleteTask(task: Task, project: Project): Observable<any> {
    return Observable.create(observer=>{
      console.log("Delete task");
      observer.next({});
    }).delay(1000);
  }
}

export class Project {
  public id: string;
}

export class Task {
  public id: string;
}
<div >
   <button (click)="delete()">Delete</button>
</div>

以下是我在控制台中看到的结果: enter image description here

请注意,我嘲笑http调用只需等待几毫秒然后返回一个对象。您可以使用执行http调用的注释方法。