0

在服务中获取所选用户详细信息的方法是:'getSelectedUser(name)',它使用一个 Observable,在所需的组件中,我们调用该服务并应用 switchMap,然后订阅它。但不知何故,它没有被订阅,它在控制台上抛出 404。请指导在没有任何错误的情况下获得该响应。

预期输出是:当我们点击特定用户时,它应该重定向到 about/username(这里:about/Kylie),显示 Kylie 的全部详细信息。

这是我的代码:

about.component.ts

import { Component, OnInit } from '@angular/core';
import { CommonService } from "./app.service";
import { ActivatedRoute, Router } from "@angular/router";

@Component({
    selector: 'about-comp',
    template: `
                <div *ngIf="users">
                    <div class="col-sm-4" *ngFor="let user of users">
                        <div class="content" [routerLink]="['/about',user.name]">
                            <h2>{{user.name}}</h2>
                        </div>
                    </div>
                </div>
    `,
    styles: [ `
        .content {
            background: #f3f3f3;
            border-radius: 4px;
            padding: 30px;
            text-align: center;
        }

    `]
})

export class AboutComponent implements OnInit {
    private users;

    constructor(private _cService: CommonService,
    private _activatedRoute: ActivatedRoute, 
    private _router:Router) {}
    ngOnInit() {
        this._cService.getUsers().subscribe(
            responseUsers => this.users = responseUsers
        )
    }


}

关于-user.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router, Params } from "@angular/router";
import { CommonService } from "./app.service";
import { Location } from '@angular/common';
import 'rxjs/add/operator/switchMap';

@Component({
    selector: 'about-user-comp',
    template:  `
                <div *ngIf="selectedUser">
                    {{selectedUser}} is the selected user  <br>
                    <button class="btn btn-primary" (click)="goBack()"> Go Back </button>
                </div>
                <div *ngIf="!selectedUser">jhjkchd</div>
    `
})

export class AboutUserComponent implements OnInit {
    private selectedUser;
    constructor(private _cService: CommonService,
    private _activatedRoute: ActivatedRoute, 
    private _router:Router,
    private _location: Location) {}
    ngOnInit() {
        //Using snapshot
        // let user = this._activatedRoute.snapshot.params['name'];
        // this.selectedUser = user;

        //Using Observable
        this._activatedRoute.params.switchMap((param:Params) => this._cService.getSelectedUser(param['name']))
            .subscribe(resp => {
                this.selectedUser = resp
                console.log(resp);
            } 
        )
    }

    goBack() {
        this._location.back();
    }
}

应用服务.ts

import { Injectable } from '@angular/core';
import { Http } from "@angular/http";
import 'rxjs/add/operator/map';
import { Observable } from "rxjs/Observable";
import { Users } from "./user";


@Injectable()

export class CommonService {
    constructor(private _http: Http) {}

    private UserUrl = 'api/Users';

    getUsers() : Observable<Users[]> {
        return this._http.get(this.UserUrl).map(
            respUsers => respUsers.json().data as Users[]
        )
    }

    getSelectedUser(name:string) : Observable<Users> {
        const selUser = `${this.UserUrl}/${name}`;
        return this._http.get(selUser).map(
            response => response.json().data as Users
        )
    }
}

in-memory.service.ts

import { InMemoryDbService } from 'angular-in-memory-web-api';

export class MemoryDataService implements InMemoryDbService {
    createDb() {
        const Users = [
           {"id": 1, "name":"Chris", "gender":"M"},
           {"id": 2, "name":"Kylie", "gender":"F"},
           {"id": 3, "name":"Christina", "gender":"F"},
        ];
        return { Users };
    }
}

app.routing.ts

import { Routes, RouterModule } from '@angular/router';
import { ModuleWithProviders } from "@angular/core";
import { HomeComponent } from "./home.component";
import { AboutComponent } from "./about.component";
import { ContactsComponent } from "./contacts.component";
import { AboutUserComponent } from "./about-user.component";

export const appRoutes = [
    {path: 'home', component: HomeComponent },
    {path: 'about', component: AboutComponent},
    {path: 'contacts', component: ContactsComponent},
    {path: 'about/:name', component: AboutUserComponent}
];

export const AppRouting : ModuleWithProviders = RouterModule.forRoot(appRoutes);

以下是屏幕截图: 单击 Kylie 用户后的第一个屏幕错误屏幕

4

0 回答 0