Javascript 角度2-查看单个数据记录
我对Angular是个新手,所以我很难弄清楚我的问题是如何形成的,因为我想完成什么,但现在就来了 我有一个组件正在从服务获取单个用户记录。然后我想在我的UI上显示这些用户详细信息。在我代码的其他部分中,它们总是多条记录,因此我使用了Javascript 角度2-查看单个数据记录,javascript,angular,Javascript,Angular,我对Angular是个新手,所以我很难弄清楚我的问题是如何形成的,因为我想完成什么,但现在就来了 我有一个组件正在从服务获取单个用户记录。然后我想在我的UI上显示这些用户详细信息。在我代码的其他部分中,它们总是多条记录,因此我使用了*ngFor,并在数据数组中循环。然而,由于这只是一个单一的结果,我不太确定如何做到这一点 组件: import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute,
*ngFor
,并在数据数组中循环。然而,由于这只是一个单一的结果,我不太确定如何做到这一点
组件:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { UserRecord } from '../shared/user-record.interface';
import { UserService } from '../shared/user.service';
@Component({
selector: 'app-view-record',
templateUrl: './view-record.component.html',
styleUrls: ['./view-record.component.css']
})
export class ViewRecordComponent implements OnInit {
private record: UserRecord[];
private errorMessage: any = '';
private loaded = false;
private RecordID: number; // User ID of who we are looking at
constructor(private _crudService: UserService,
private activatedRoute: ActivatedRoute) { }
ngOnInit() {
// Get the userID from the activated route
this.activatedRoute.params.subscribe((params: Params) => {
this.RecordID = params['id'];
});
// Call our service and pass the userID
this._crudService.getRecord(this.RecordID)
.then(res => {
this.record = this._crudService.record;
return this._crudService.getRecord(this.RecordID);
})
.then(res => {
console.log(this.record)
this.loaded = true;
})
.catch(err => { console.error(err); });
}
}
getRecord(userID: number) {
const headers: Headers = new Headers({
"Authorization": this._frameworkService.getSessionInfo().token
});
return new Promise((resolve, rejects) => {
this._http.post(this.baseUrl + '/fetchRecord', { "userID": userID }, { "headers": headers })
.map(res => res.json())
.subscribe((data) => {
if (data) {
this.record = data;
}
resolve(true);
});
});
}
export interface UserRecord {
RecordID: number;
QID: string;
FavoriteColor?: string;
FavoriteNumber?: number;
FavoriteActor?: string;
MetaInsertUTC: string;
MetaUpdateUTC: string;
FirstName: string;
LastName: string;
NTID: string;
}
服务:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { UserRecord } from '../shared/user-record.interface';
import { UserService } from '../shared/user.service';
@Component({
selector: 'app-view-record',
templateUrl: './view-record.component.html',
styleUrls: ['./view-record.component.css']
})
export class ViewRecordComponent implements OnInit {
private record: UserRecord[];
private errorMessage: any = '';
private loaded = false;
private RecordID: number; // User ID of who we are looking at
constructor(private _crudService: UserService,
private activatedRoute: ActivatedRoute) { }
ngOnInit() {
// Get the userID from the activated route
this.activatedRoute.params.subscribe((params: Params) => {
this.RecordID = params['id'];
});
// Call our service and pass the userID
this._crudService.getRecord(this.RecordID)
.then(res => {
this.record = this._crudService.record;
return this._crudService.getRecord(this.RecordID);
})
.then(res => {
console.log(this.record)
this.loaded = true;
})
.catch(err => { console.error(err); });
}
}
getRecord(userID: number) {
const headers: Headers = new Headers({
"Authorization": this._frameworkService.getSessionInfo().token
});
return new Promise((resolve, rejects) => {
this._http.post(this.baseUrl + '/fetchRecord', { "userID": userID }, { "headers": headers })
.map(res => res.json())
.subscribe((data) => {
if (data) {
this.record = data;
}
resolve(true);
});
});
}
export interface UserRecord {
RecordID: number;
QID: string;
FavoriteColor?: string;
FavoriteNumber?: number;
FavoriteActor?: string;
MetaInsertUTC: string;
MetaUpdateUTC: string;
FirstName: string;
LastName: string;
NTID: string;
}
界面:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { UserRecord } from '../shared/user-record.interface';
import { UserService } from '../shared/user.service';
@Component({
selector: 'app-view-record',
templateUrl: './view-record.component.html',
styleUrls: ['./view-record.component.css']
})
export class ViewRecordComponent implements OnInit {
private record: UserRecord[];
private errorMessage: any = '';
private loaded = false;
private RecordID: number; // User ID of who we are looking at
constructor(private _crudService: UserService,
private activatedRoute: ActivatedRoute) { }
ngOnInit() {
// Get the userID from the activated route
this.activatedRoute.params.subscribe((params: Params) => {
this.RecordID = params['id'];
});
// Call our service and pass the userID
this._crudService.getRecord(this.RecordID)
.then(res => {
this.record = this._crudService.record;
return this._crudService.getRecord(this.RecordID);
})
.then(res => {
console.log(this.record)
this.loaded = true;
})
.catch(err => { console.error(err); });
}
}
getRecord(userID: number) {
const headers: Headers = new Headers({
"Authorization": this._frameworkService.getSessionInfo().token
});
return new Promise((resolve, rejects) => {
this._http.post(this.baseUrl + '/fetchRecord', { "userID": userID }, { "headers": headers })
.map(res => res.json())
.subscribe((data) => {
if (data) {
this.record = data;
}
resolve(true);
});
});
}
export interface UserRecord {
RecordID: number;
QID: string;
FavoriteColor?: string;
FavoriteNumber?: number;
FavoriteActor?: string;
MetaInsertUTC: string;
MetaUpdateUTC: string;
FirstName: string;
LastName: string;
NTID: string;
}
服务结果:
[
{
"RecordID":"55",
"QID":"Q00019204",
"FavoriteColor":"Blue",
"FavoriteNumber":"6",
"FavoriteActor":"Bob",
"MetaInsertUTC":"2017-06-29 18:47:01.750",
"MetaUpdateUTC":null,
"FirstName":"Jim",
"LastName":"Bobs",
"NTID":"bobby"
}
]
在我的组件HTML中,我尝试了{{record.FirstName}
,但收到了ViewRecordComponent.HTML:16错误类型错误:无法读取未定义的
的属性“FirstName”
因为这不是一组数据结果,所以我不知道*ngFor
在用例中如何适用
我假设,由于我的组件将数据存储在记录
对象中,所以我应该能够从UI访问它?console.log
显示所有正确的数据点
如何在我的组件HTML中引用用户
FirstName
?希望我至少走的是正确的道路。从Http获取数据是异步的。这意味着当页面第一次显示时,数据还没有出现
有几种方法可以解决此问题:
一个选项是使用“?”(安全导航)操作符:{{{record?.FirstName}}
这可以更好地处理空值。有关更多信息,请参阅此链接:
另一种选择是在HTML代码中使用*ngIf<代码>*ngIf='record'
所以,当您的页面第一次显示时,它不会生成记录尚未设置的错误。一旦检索到数据,绑定就会注意到更改并相应地更新UI
以下是我的一种服务方法:
getProducts(): Observable<IProduct[]> {
return this._http.get(this._productUrl)
.map((response: Response) => <IProduct[]> response.json())
.catch(this.handleError);
}
getProducts():可观察{
返回此。\ http.get(此。\产品URL)
.map((response:response)=>response.json())
.接住(这个.把手错误);
}
以下是对该服务的呼叫:
ngOnInit(): void {
this._productService.getProducts()
.subscribe(products => this.products = products,
error => this.errorMessage = <any>error);
}
ngOnInit():void{
这是._productService.getProducts()
.subscribe(products=>this.products=products,
error=>this.errorMessage=error);
}
请注意,订阅位于调用服务的组件中,而不是服务本身。您的响应似乎是一个带有对象的数组,因此
记录。FirstName
不存在,但记录[0]。FirstName
存在
在查看时,请记住使用安全导航操作符或*ngIf
,以免遇到DeborahK提到的未定义问题
此外,只是一些建议,如何处理http的角度。。。我会做如下的事情
getRecord(userID: number) {
const headers: Headers = new Headers({
"Authorization": this._frameworkService.getSessionInfo().token
});
return this._http.post(this.baseUrl + '/fetchRecord', { "userID": userID }, { "headers": headers })
.toPromise()
.then(res => res.json()[0]) // get the object only
.catch(err => { console.error(err); });
}
和组成部分:
this._crudService.getRecord(this.RecordID)
.then(res => {
this.record = res;
});
但这完全取决于您:)所以我尝试添加
来包装我的数据。我在componet服务调用中使用将其设置为true,然后(res=>{this.loaded=true;})
。虽然不再在控制台中抛出错误,但也不会显示数据点。我想这是一个小小的进步。为什么要使用单独的属性呢?只需检查您的“记录”属性。那么你就不必担心设置/清除加载的属性了。好的,我改变了这一点。现在错误已经消失,我将处理结果集,并尝试确定它为什么没有显示出来。谢谢你的提示!我的服务看起来有点不同。我把它添加到我上面的答案中。