[英]how to generate dynamic menu and components in angular based on API response
我想(適當地)根據 API 響應動態生成一些菜單位置和引用這些菜單位置的組件。 對 c# 后端的響應將在 app.component.ts 中的應用程序啟動時進行。 這些菜單位置將是處理項目的狀態(例如“完成”、“進行中”等),並且每個組件中的 html 看起來幾乎相同(只是表格中的位置來自 sql 數據庫,它們之間的唯一區別是對 ZAC5C74B64B4B83252EF2 進行查詢具有不同“where”子句的數據庫)。 現在是兩個狀態,但將來可能會再增加 7 個,所以我不想每次在后端添加新狀態時都在 angular 中創建一個新組件。 那么我應該尋找什么? 在收到 api 的回復后,我應該在哪里存儲這個答案? (為了始終擁有這些組件,我不希望它們在頁面重新加載或其他任何事情后消失)。
When displaying data fetched from an API it's good practice to implement a model controller view pattern where the date is downloaded by the controller (a service), saved in the model which is marked with the @Injectable()
decortator and is injected in the view您正在顯示數據的組件。 因此,您獲取的數據存儲在 model 中,並且可以在您需要的任何地方訪問。
controller 可能看起來像這樣:
@Injectable({
providedIn: 'root'
})
export class StatusService{
constructor(private http : HttpClient)
{ }
public getStatus() : Observable<any>
{
return this.http.get('http://myapi.com/getstatus');
}
}
model 只是存儲這些數據:
export class Status
{
public id : number;
public type: string;
}
@Injectable()
export class StatusModel
{
public statuses: Status[];
constructor(private statusService : StatusService)
{ }
public getStatus() : Observable<Status[]>
{
return this.statusService.getstatus().pipe(map((status: Status[]) =>
{
this.statuses = data;
return this.statuses ;
}));
}
}
在您的組件(視圖)中,您將在構造函數中注入 StatusModel 並發出 API 請求:
@Component({
selector: 'app-status',
templateUrl: './status.component.html',
styleUrls: ['./status.component.scss'],
})
export class StatusComponent implements OnInit {
constructor(public statusModel : StatusModel)
{
this.getStatus();
}
public getStatus() : void
{
this.statusModel.getStatus().subscribe(
(data) =>
{
console.log(data);
},
(error) =>
{
console.log(error);
}
);
}
}
在您的 HTML 中,您可以使用*ngFor顯示存儲在 statusModel.statuses 中的這些狀態,如下所示:
<div class="status" *ngFor="let status of statusModel.statuses">
<p>{{status.id}</p>
<p>{{status.type}}</p>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.