this.route.snapshot.params.id.switchMap不是Angular2

时间:2017-09-12 13:20:39

标签: javascript angular angular2-routing

我正在使用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);
        });
    }
}

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

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