我试图获取从我的web-api获取的数据,以便在我的HTML中显示。 我有一个用于列出事件的组件,第二个用于详细事件。
当我点击活动时,页面会路由到我的新网址+ ID,但我会在我的详细信息页面中注明。 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 :(得分: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 !
});
}