我正在嘗試在前端顯示我的資料(食譜)。當我從服務器獲得的 console.log(data) 我有包含物件陣列的'msg'屬性的物件..我可以訪問該陣列data['msg' as keyof typeof data])
所以當我console.log我得到一個記錄msg的物件陣列資料的屬性
現在我的問題是當我嘗試將該陣列分配給this.recipe陣列時。當我嘗試時this.recipe = data['msg' as keyof typeof data]出現錯誤:
型別 'Function' 缺少型別 'Recipe[]' 中的以下屬性:pop、push、concat、join 等 27 個。
但是當我嘗試使用 push() 我得到
“功能”型別缺少“配方”型別中的以下屬性:描述、成分
我對 Angular 比較陌生,我迷路了。如果你需要我的其他代碼塊,現在讓我,我不想復制粘貼很多,因為我不確定問題出在哪里,什么會有幫助。我把檔案放在這里問題。
我遇到問題的代碼:
export class ListComponent implements OnInit {
public recipes: Recipe[];
constructor(private _recipeService: RecipeService) { }
ngOnInit(): void {
this.readRecipes();
}
readRecipes() {
this._recipeService.readRecipes().subscribe({
next: (data) => {
this.recipes = data['msg' as keyof typeof data];
}
,
error: (error) => console.log(error),
complete: () => console.info('complete')
}
)
}
}
我的 recipe.service.ts 檔案:
export class RecipeService {
private baseUri: string = "http://localhost:8080";
private headers = new HttpHeaders().set('Content-Type', 'application/json')
constructor(private http: HttpClient) { }
createRecipe(recipe: Recipe) {
return this.http.post(this.baseUri '/create', recipe, { headers: this.headers });
}
readRecipes() {
return this.http.get(this.baseUri '/read', { headers: this.headers });
}
updateRecipe(recipe: Recipe) {
return this.http.put(this.baseUri '/update', recipe, { headers: this.headers });
}
deleteRecipe(id: string) {
return this.http.delete(this.baseUri '/delete/' id, { headers: this.headers });
}
}
讀取路由的后端代碼部分:
router.get('/read', (req, res, next) => {
Recipe.find({}, (err, recipes) => {
if (err)
res.status(500).json({
errmsg: err
});
res.status(200).json({
msg: recipes
});
});
});
uj5u.com熱心網友回復:
一個更簡單的方法是async在 Angular 中使用管道:
@Component({
template: `
<ul *ngIf="(employees$ | async).length">
<li *ngFor="let employee of employees$ | async">{{employee.name}}</li>
</ul>
`
})
export class EmployeesComponent implements OnInit {
employees$: Observable<Employee[]>;
constructor(private service: MyService) {}
ngOnInit() {
this.employees$ = this.service.getEmployees$();
}
}
這是你的 Stackblitz 的一個分支,顯示了食譜串列:https ://stackblitz.com/edit/angular-ivy-r97jph?file=src/app/components/list/list.component.ts
uj5u.com熱心網友回復:
只是在這里寫下我找到了解決方案。在后端,我發送回應為res.JSON({msg:recipes}),但我無法訪問此“msg”,但是當我將其更改為僅回應 JSON 時,僅使用 parenteses 而res.JSON(recipes)不是在前端使用data這些陣列,我可以將其分配,this.recipes=data現在正在作業
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/392334.html
