2017-03-07 132 views
0

我试图从我的web-api获取数据,以显示在我的html中。 我有一个组件列出事件和第二个细节事件。使用* ngIf获取数据 - Angular2

当我点击事件,页面路由到我的新网址+编号,但我得到在我的详细信息页注意。 ngIf应该在这里工作,而listEvent组件工作得很好。

这就是我得到:detailEvent

eventDetail.html

<li *ngIf="Ievents"> 
{{event.id}} 
<h2>works</h2> 

eventDetail.ts

import 'rxjs/add/operator/switchMap'; 
import { Component, OnInit } from '@angular/core'; 
import { ActivatedRoute, Params } from '@angular/router'; 
import { Location } from '@angular/common'; 

import { DataService, Ievents } from '../dataService'; 

@Component({ 
    moduleId: module.id, 
    selector: 'event-detail', 
    templateUrl: './eventDetail.component.html', 
    styleUrls: ['./eventDetail.component.css'] 
}) 
export class EventDetailComponent implements OnInit { 
    event: Ievents; 

    constructor(
    private dataService: DataService, 
    private route: ActivatedRoute, 
    private location: Location 
) { } 

    ngOnInit(): void { 
    this.route.params 
     .switchMap((params: Params) => this.dataService.getEvent(+params['id'])) 
     .subscribe(event => this.event = event); 
    console.log(this.event); 
    } 

} 

eventsList.ts

import 'rxjs/add/operator/switchMap'; 
import { Observable } from 'rxjs/Observable'; 
import { Component, OnInit } from '@angular/core'; 
import { Router, ActivatedRoute, Params } from '@angular/router'; 
import { Subscription } from 'rxjs/Subscription'; 

import { DataService, Ievents } from '../dataService'; 



@Component({ 
    moduleId: module.id, 
    selector: 'showevents', 
    template: require('./showEvents.component.html'), 
    styleUrls: ['./showEvents.component.css'], 
    providers: [DataService]   
}) 
export class ShowEventsComponent implements OnInit { 

    events: Observable<Ievents[]>; 
    private selectedId: number; 



    constructor(
    private service: DataService, 
    private route: ActivatedRoute, 
    private router: Router 
    ) { } 


    ngOnInit() { 
    this.events = this.route.params 
     .switchMap((params: Params) => { 
      this.selectedId = +params['id']; 
      return this.service.getEvents(); 
     }); 
    } 

    isSelected(event: Ievents) { 
    return event.id === this.selectedId; 
    } 

    onSelect(event: Ievents) { 
    this.router.navigate(['/detail', event.id]); 
    } 

eventList.html

<div class="container-fluid"> 
    <h2>Hendelser</h2> 
    <ul class="events"> 
    <li *ngFor="let event of events | async" 
     [class.selected]="isSelected(event)" 
     (click)="onSelect(event)"> 
     <span class="badge">{{ event.id }}</span> {{ event.category.name }} 
    </li> 
    </ul> 
</div> 

DataService.ts

import { Http, Response, RequestOptions, Headers } from '@angular/http'; 
import 'rxjs/add/operator/map' 
import { Observable, Subject } from 'rxjs/Rx'; 
import { Injectable } from '@angular/core'; 
import 'rxjs/add/operator/toPromise'; 





@Injectable() 
export class DataService { 

    constructor(private _http: Http) { } 
    private RegenerateData = new Subject<number>(); 
    private actionUrl = 'http://localhost:53708/api/'; 


    getCategories(): Promise<Icategories[]> { 
    return this._http.get(this.actionUrl + "categories") 
     .toPromise() 
     .then(response => this.extractArray(response)) 
     .catch(this.handleErrorPromise); 
    } 



    getEvents(): Promise<Ievents[]> { 
    return this._http.get(this.actionUrl + "events") 
     .toPromise() 
     .then(response => this.extractArray(response)) 
     .catch(this.handleErrorPromise); 
    } 

    getEvent(id: number): Promise<Ievents> { 
    const url = `${this.actionUrl + "events" }/${id}`; 
    return this._http.get(url) 
     .toPromise() 
     .then(response => response.json().data as Ievents) 
     .catch(this.handleErrorPromise); 
    } 


    Add(model) { 
    let headers = new Headers({ 
     'Content-Type': 
     'application/json; charset=utf-8' 
    }); 
    let options = new RequestOptions({ headers: headers }); 
    delete model["id"]; 
    let body = JSON.stringify(model); 
    return this._http.post(this.actionUrl + "events", body, 
     options).toPromise().catch(this.handleErrorPromise); 
    } 





    protected extractArray(res: Response, showprogress: boolean = true) { 
    let data = res.json(); 
    return data || []; 
    } 

    protected handleErrorPromise(error: any): Promise<void> { 
    try { 
     error = JSON.parse(error._body); 
    } catch (e) { 
    } 

    let errMsg = error.errorMessage 
     ? error.errorMessage 
     : error.message 
      ? error.message 
      : error._body 
       ? error._body 
       : error.status 
        ? `${error.status} - ${error.statusText}` 
        : 'unknown server error'; 

    console.error(errMsg); 
    return Promise.reject(errMsg); 
    } 
} 

export interface Ievents { 
    id: number, 
    name: string, 
    whathh: string, 
    category: string, 
    tlf: string 
} 

export interface Icategories { 
    id: number; 
    name: string; 
} 
+0

和你有什么期待什么呢? – OmarIlias

回答

0
<li *ngIf="event"> 

您要检查,如果你的组件变量event设置,没有别的! :)

你可以做到这一点也是这样:

<li> 
{{event?.id}} 
<h2>works</h2> 

另一个提示:

ngOnInit(): void { 
    this.route.params 
     .switchMap((params: Params) => this.dataService.getEvent(+params['id'])) 
     .subscribe(event => { 
      this.event = event; 
      console.log(this.event); // print it here ! 
     }); 

    } 
+0

嗯,没有工作。我所得到的只是“作品” – hhkon1

+0

,那么你的'事件'是空的或未定义的。 – mxii