【发布时间】:2018-08-13 23:07:22
【问题描述】:
我目前正在关注 Jogesh Muppala 在 Coursera 上的 Angular 课程,问题在于以下代码行。
this.route.params.pipe(switchMap((params: Params) => this.dishService.getDish(+params['id'])))
其余代码如下。到目前为止,我的理解是 this.route.params 是一个 Observable,并且 this.dishService.getDish(+params[id]) 也将返回一个 Observable。我的问题是了解 (params: Params) 是如何到达那里的。它用作箭头函数中的参数,并且在语句末尾附近被 getDish 函数使用。但是,在行的开头,我们只能通过 this.route.params 访问 params。它是不同的参数吗?类型声明 params: Params 使它看起来像是一个全新的 Params 类型实例。但是如果是这样,getDish怎么会使用它呢?
import { Component, OnInit} from '@angular/core';
import {Params, ActivatedRoute} from '@angular/router';
import {Location} from '@angular/common';
import{ Dish} from '../shared/dish';
import { DishService} from '../services/dish.service';
import { switchMap } from 'rxjs/operators';
@Component({
selector: 'app-dishdetail',
templateUrl: './dishdetail.component.html',
styleUrls: ['./dishdetail.component.scss']
})
export class DishdetailComponent implements OnInit {
dish: Dish;
dishIds: number[];
prev: number;
next: number;
constructor(private dishService: DishService, private route: ActivatedRoute,
private location: Location) {
}
ngOnInit() {
this.dishService.getDishIds().subscribe(dishIds => this.dishIds = dishIds);
this.route.params.pipe(switchMap((params: Params) => this.dishService.getDish(+params['id'])))
.subscribe(dish => { this.dish = dish; this.setPrevNext(dish.id); });
}
setPrevNext(dishId: number) {
const index = this.dishIds.indexOf(dishId);
this.prev = this.dishIds[(this.dishIds.length + index - 1) % this.dishIds.length];
this.next = this.dishIds[(this.dishIds.length + index + 1) % this.dishIds.length];
}
goBack(): void{
this.location.back();
}
}
感谢您的阅读。
【问题讨论】:
标签: angular rxjs angular2-observables