我正在嘗試構建一個ASP.NET用作后端(API)的應用程式并Angular構建我的應用程式的前端。
這是我在 API 中的控制器,用于從資料庫中分別獲取單個用戶的用戶串列。
[HttpGet]
public async Task<ActionResult<IEnumerable<User>>> Get()
{
return await _dbContext.Users.ToListAsync();
}
[HttpGet("{id}")]
public async Task<ActionResult<User>> GetUser(int id)
{
return await _dbContext.Users.FindAsync(id);
}
在Angular組件的.ts檔案中,我添加了以下代碼:
export class Component1 implements OnInit {
users: any;
constructor(private http: HttpClient) { }
ngOnInit(): void {
this.getUsersList();
}
getUsersList() {
this.http.get('https://localhost:44357/api/').subscribe(response =>
{
this.users = response;
}, error => {
console.log(error);
})
}
在.html組件的檔案中,我添加了以下代碼片段并設法回傳資料庫中所有用戶名稱的串列。
<div class="d-flex justify-content-center">
<select class="form-select">
<option *ngFor ="let user of users">{{user.name}}</option>
</select>
</div>
我現在的問題是我想從另一個組件中的單個用戶回傳一個屬性(例如name屬性)。
這是 .html 檔案:
<div class="d-flex justify-content-center">
<form>
<input class = "textbox" type="text" name="Name" value="0">
</form>
</div>
這是該.ts組件的檔案:
export class Component2 implements OnInit {
user: any;
constructor(private http: HttpClient) { }
ngOnInit(): void {
this.getUser();
}
getUser() {
this.http.get('https://localhost:44357/api/{id}').subscribe(response =>
{
this.user = response;
}, error => {
console.log(error);
})
}
}
我想在文本框中回傳單個用戶(存盤在資料庫中)的屬性。有什么想法我該怎么做?
uj5u.com熱心網友回復:
添加ngModel到您的輸入控制元件:
<div class="d-flex justify-content-center">
<form>
<input class = "textbox" type="text" [(ngModel)]="user.name" name="name">
</form>
</div>
并添加FormsModule到您的AppModule課程中
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
...
FormsModule
],
declarations: [
...
],
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule { }
uj5u.com熱心網友回復:
分配user.name給標簽中的value屬性<iput>
<div class="d-flex justify-content-center">
<form>
<input class = "textbox" type="text" name="Name" value="user.name">
</form>
</div>
筆記
盡量不要使用anytype 以避免在運行時出現潛在問題。您可以為模型
創建介面User
用戶.ts
export interface User{
UserName: string;
//other properties
}
然后users宣告user如下
users: Users[];
user: User;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/436040.html
