Angular2:订阅observable截断服务响应--路由

Angular 2: Subscribe to observable truncating service response -- routing

我正在练习 angular 2.x 服务和路由。我使用路由器导航到 URL,然后尝试传递从 ActivatedRoute 获取的 URL 参数,以从 WhichnailService 服务获取字符串。但是,WhichnailComponent 中的.subscribe() 的响应只有要返回的字符串的最后一个索引。

当我记录服务本身时,它有完整的字符串

import {Component} from '@angular/core';
import {Router, ActivatedRoute, Params} from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/switchMap';
import {WhichnailService} from './whichnail.service';


@Component({
    selector: 'whichnail-component',
    template: `
    <h1> welcome to the Whichnail Component </h1>
    <h1> The nail is {{ nail }} </h1>
    `
}) 
export class WhichnailComponent {
    nail:string;
    selectedNail:number;
    constructor(private router: Router, private route: ActivatedRoute, private service: WhichnailService) {
    }

    ngOnInit() {
        this.route.params
    // (+) converts string 'id' to a number
        .switchMap((params: Params) => this.service.getNail(this.selectedNail = +params['id']))
        .subscribe((nail:string) => this.nail = nail);
    }
}

这是服务本身:

import {Injectable} from '@angular/core';

@Injectable()

export class WhichnailService {
    listOfNails = ["Invalid", "Thumb", "Index", "Middle", "Ring", "Pinky"];

    getNail(index: number):string {
        console.log(index);
        console.log(this.listOfNails[index]);
        return this.listOfNails[index];
    }
}

我做错了什么?

I need to return an Observable.of from my service.

因为您只能订阅一个Observable。这就是为什么,即使 return 一个不需要异步(或可观察)过程的普通值,您也需要用一个可观察的来包装它,以便它可以被订阅。这样做的方法是使用 Observable.of

如果您的服务不需要可观察操作,您可以不使用。只需订阅您的 routeparams 并更新值:

ngOnInit(){
 this.route.params
   .subscribe((params: Params) => {
    //assign the value directly
    this.nail = this.service.getNail(this.selectedNail = +params['id'])
   })
}

在您的服务中,您不需要Observable.of

包装它
export class WhichnailService {
    listOfNails = ["Invalid", "Thumb", "Index", "Middle", "Ring", "Pinky"];

    getNail(index: number):string {
        return this.listOfNails[index]; //no need to wrap with Observable.of
    }
}