【问题标题】:this.route.snapshot.params.id.switchMap is not a function Error in Angular2this.route.snapshot.params.id.switchMap 不是 Angular2 中的函数错误
【发布时间】:2017-09-12 13:20:39
【问题描述】:

我正在使用 Angular2 构建 POC。

这是我的路线的样子:

RouterModule.forRoot([
{
  path:'',
  redirectTo:'app',
  pathMatch:'full',
},
{
  path:'contact-list',
  component:ContactsListComponent
},
{
  path:'contact-details/:id',
  component:ContactCardComponent
}])

在我的ContactsListComponent 中,我正在循环访问从服务中获取的数据。

    <li *ngFor = "let contact of contacts ;trackBy : trackById;let i = index;let c = count;let e = even; let o = odd;"
      [ngClass] = "{
        odd : o,
        even: e
      }">
      Index : {{i}}
      Count : {{c}}
      <a [routerLink] = "['/contact-details',contact.id]">
        {{contact.name}}
      </a>
    </li>
  </ul>

现在,ContactCardComponent

import { Component,Input,Output,EventEmitter,OnInit } from '@angular/core';
import { Contact } from './contact';
import { ActivatedRoute } from '@angular/router';
import { ContactService } from './contact-service';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';

@Component({
    selector:'contact-card',
    template:`
        <div class="contact-card">
            <p>{{ selectedContact.name }} ( {{ selectedContact.age }} )</p>
            <p>{{ selectedContact.email }}</p>
        </div>
        <button (click) = "sendNotification()">Notify my parent!</button>        
        `,
    providers:[ContactService]
})

export class ContactCardComponent implements OnInit{
    id : string;
    selectedContact : Contact;

    @Output() notifyParentComponent : EventEmitter<any> = new EventEmitter();

    constructor(private route : ActivatedRoute,private _contactService : ContactService){
    } 

    ngOnInit(){
        this.selectedContact = this.route.snapshot.params['id']
            .switchMap(id => this._contactService.getContact(id))
            .subscribe(contact => this.selectedContact = contact);
    }
    sendNotification(){
        this.notifyParentComponent.emit('Emitted some value to the parent');
    }
}

上面写着error_handler.js:54 EXCEPTION: Uncaught (in promise): Error: Error in :0:0 caused by: this.route.snapshot.params.id.switchMap is not a function Error: Error in :0:0 caused by: this.route.snapshot.params.id.switchMap is not a function

我做错了什么? 有人可以解释一下逻辑吗?

编辑

服务看起来像:

import {Injectable} from '@angular/core';
import { Contact } from './contact';
import { Contacts } from './mock-contacts';

@Injectable()
export class ContactService{
    getContacts() : Contact[]{
        return Contacts;
    } 

    getContact(id : number) : Promise<Contact>{
        return this.getContactsSlowly().
            then(contacts => contacts.find(contact => contact.id == id));
    }

    getContactsSlowly() : Promise<Contact[]> {
        return new Promise(resolve => {
            setTimeout(() => resolve(this.getContacts()),1000);
        });
    }
}

【问题讨论】:

  • this.route.params.id.switchMap而不是this.route.snapshot.params.pluck("id").switchMap会起作用

标签: javascript angular angular2-routing


【解决方案1】:

route.snapshot 顾名思义是路由的快照,上面没有 Observable 属性。

所以你可以这样做:(注意你需要在你的ts文件中import 'rxjs/add/operator/pluck'

this.route.params.pluck('id')
            .switchMap((id: number) => Observable.fromPromise(this._contactService.getContact(id)))
            .subscribe(contact => this.selectedContact = contact);

或者像这样:

this._contactService.getContact(+this.route.snapshot.params['id'])
            .then(contact => this.selectedContact = contact);

【讨论】:

  • 第二种方法说Property 'subscribe' does no t exist on type 'Promise&lt;Contact&gt;'
  • 第一种方法是Property 'pluck' does not ex ist on type 'Observable&lt;Params&gt;'
  • import 'rxjs/add/operator/pluck';
  • "Promise' 类型上不存在属性 'subscribe'" 我猜您的服务正在返回一个 Promise。那你就不需要订阅了……
  • 我需要将 id 转换为数字,因为 getContacts 接受数字。
【解决方案2】:

试试

this.route.paramMap
            .switchMap((params: ParamMap) => this._contactService.getContact(+params.get('id')))
            .subscribe(contact => this.selectedContact = contact)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多