Angular 2:订阅可观察的截断服务响应 - 路由

时间:2017-06-27 23:00:24

标签: angular angular2-routing angular2-services

我正在练习角度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];
    }
}

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

  

我需要从我的服务中返回一个Observable.of。

因为您只能订阅Observable。这就是为什么,即使返回一个不需要异步(或可观察)进程的普通值,你需要用一个observable包装它以便它可以被订阅。这样做的方法是使用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
    }
}