[我尝试了几次Angular在线课程后尝试创建我的第一个应用程序,所以我对此非常满意。
我想做什么:
我正在尝试创建一个具有应用程序名称标题的表,并且在每个应用程序名称下方是该应用程序所组成的组件的列表。因此,每个应用程序下至少要列出一个组件。
我有3个组成部分:
我的计划是让APP调用API并检索应用程序列表(标识和名称)(比方说3)。然后,我尝试调用另一个API,该API将从APPLICATION ITEMS组件检索该特定应用程序的项目列表,并将其显示在该组件APPLICATION APPLICATIONS的该表下。
出什么问题?
第一部分有效,我将应用程序名称传递给组件。失败的部分是我尝试调用第二个API检索项目的地方。我似乎无法从父代传递来的ID包含在API调用中。
app.component.ts
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
appURL: string = 'http://localhost:3333/application'
appsName = []
appsID = []
constructor(private http: HttpClient) {
this.http.get(this.appURL).toPromise().then(data => {
for (let key in data){
if (data.hasOwnProperty(key)){
this.appsID.push(data[key].id)
console.log("ID = " + data[key].id)
this.appsName.push(data[key].name)
console.log("Name = " + data[key].name)
}
}
})
}
}
*控制台返回:
ID = 1
Name = This Website
ID = 2
Name = Google
ID = 3
Name = My Website
applicationitems.component.ts
import { Component, Input } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-statuscarditems',
templateUrl: './statuscarditems.component.html',
styleUrls: ['./statuscarditems.component.css']
})
export class StatuscarditemsComponent {
@Input() appsID: number
appURL: string = 'http://localhost:3333/application/item/' + this.appsID
appItems = []
constructor(private http: HttpClient) {
// Retrieve List of Applications from the database
this.http.get(this.appURL).toPromise().then(data => {
for (let key in data){
if (data.hasOwnProperty(key)){
this.appItems.push(data[key].name)
console.log("Name = " + data[key].name)
}
}
})
}
}
此例中的URL变为:http://localhost:3333/application/item/ undefined
[我知道我的方法是错误的,但是,这是我的新手,我正在努力弄清楚我要去哪里,而且令人沮丧,因为我知道这应该很容易,而且对我来说很明显。
任何帮助将不胜感激。预先感谢。
retreiveData()
进行http调用。您也可以添加条件,以防由于某种原因未定义数字,但我没有提供它。_appId: number
appURL: string
@Input() set appsID(id: number) {
this._appId = id; //pretty much useless here
this.appUR = 'http://localhost:3333/application/item/' + id
this.retreiveData();
}
retreiveData() {
this.http.get(this.appURL).toPromise().then(data => {
for (let key in data){
if (data.hasOwnProperty(key)){
this.appItems.push(data[key].name)
console.log("Name = " + data[key].name)
}
}
})
}