【问题标题】:Pass first item of subscribed data to service将订阅数据的第一项传递给服务
【发布时间】:2018-10-11 09:57:47
【问题描述】:

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

我的视图有 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])
          }
        });
  }

【问题讨论】:

    标签: javascript angular typescript rxjs angular-observable


    【解决方案1】:

    您的问题是您在调用subscribe 时没有为complete 回调使用箭头函数。如您所见,您正在为nexterror 使用箭头函数。

    当您使用function(...) {...} 定义一个新函数时,您正在创建一个新上下文,因此this 关键字改变了它的含义。箭头函数和普通函数之间的区别(除了更优雅,在我看来)是箭头函数没有为this 定义新的上下文,因此该关键字的含义与它们在上下文中的含义相同定义。因此,在您的nexterror 回调中,this 是您的组件,但在您对complete 的调用中,this 肯定是对window 的引用,它没有@ 987654334@ 属性,因此是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 关键字,因为该函数没有参数,但您可以使用语法() =&gt; expression() =&gt; {...} 来表达它

    data =&gt; this.items = data毕竟是一种更简单优雅的写法

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

    【讨论】:

    • 感谢您的回答和解释!
    猜你喜欢
    • 2020-08-12
    • 1970-01-01
    • 2016-08-21
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多