首页 > 解决方案 > 将订阅数据的第一项传递给服务

问题描述

我正在开发需要应用以下机制的角度应用程序:

我的视图有 2 个部分(项目列表和选定项目的详细信息)。用户可以单击某个项目,下一个服务会获取该项目的附加数据并在详细视图中显示它们。如果可用,我还想在开始时自动选择第一个项目。

这是我的服务:

@Injectable()
export class ItemService {

  private url: string;
  private itemSource = new BehaviorSubject<Item>(null);
  selectedItem = this.itemSource.asObservable();

  constructor(private http: HttpClient) {
    this.url = 'http://localhost:8080/api/item';
  }

  getItems(): Observable<Item[]> {
    let observable = this.http.get<Item[]>(this.url)
      .map(items => items.map(item => {
        return new Item(item);
      }));
    return observable;
  }

  selectItem(item: Item) {
    return this.http.get<Item>(this.url + '/' + item.id)
      .map(item => new Item(item))
      .subscribe(t => this.itemSource.next(t));
  }
}

在详细组件中,我正在订阅这样的选定项目:

  ngOnInit() {
    this.itemService.selectedItem.subscribe(item => this.selectedItem = item);
  }

以下代码来自我显示项目列表的组件。我还想在订阅数据后设置选定的项目,但我的代码不起作用。我在 html 模板中迭代 items[] 属性并显示数据,但是当我在订阅数据后访问这个数组时,我得到了未定义的结果。你能修复我的代码吗?谢谢!

  public items = [];

  constructor(private itemService: ItemService) { }

  ngOnInit() {
    this.itemService.getItems()
      .subscribe(
        data => this.items = data,
        err => console.log(err),
        function () {
          console.log('selected data', this.items); // this prints undefined
          if (this.items && this.items.length) {
            this.itemService.selectedItem(this.items[0])
          }
        });
  }

标签: javascriptangulartypescriptrxjsangular-observable

解决方案


您的问题是您complete在调用subscribe. 如您所见,您正在为next和使用箭头函数error

当您定义一个新函数时,function(...) {...}您正在创建一个新上下文,因此this关键字会改变其含义。箭头函数和普通函数之间的区别(除了更优雅,在我看来)是箭头函数没有为 定义新的上下文this,因此该关键字的含义与它们定义的上下文相同。因此,在您的nexterror回调中,this是您的组件,但在您对 , 的调用中completethis最肯定的是对 的引用window,它没有items属性,因此undefined.

将您的代码更改为:

public items = [];

constructor(private itemService: ItemService) { }

ngOnInit() {
  this.itemService.getItems()
  .subscribe(
    data => this.items = data,
    err => console.log(err),
    () => {
      console.log('selected data', this.items); // this prints undefined
      if (this.items && this.items.length) {
        this.itemService.selectedItem(this.items[0])
      }
    });
}

我想你在那里使用了function关键字,因为该函数没有参数,但你可以用语法来表达() => expression,或者() => {...}

data => this.items = data,毕竟是一种更简单更优雅的写法

(data) => { return this.items = data; }

推荐阅读