Currently, I am working on developing an application that utilizes ASP.NET
for the Back End (API) and Angular
for the Front End of the application.
Within the API, I have set up controllers to retrieve either a list of users from the database or a single user.
[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);
}
On the Angular
side, I have added the following code snippet to the component's .ts
file:
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);
})
}
Furthermore, in the component's .html
file, I have included the following code to display a list of all user names from the database:
<div class="d-flex justify-content-center">
<select class="form-select">
<option *ngFor ="let user of users">{{user.name}}</option>
</select>
</div>
Currently, my challenge lies in returning a specific property (such as the name property) of a single user in another component.
Below is the .html
file for that component:
<div class="d-flex justify-content-center">
<form>
<input class = "textbox" type="text" name="Name" value="0">
</form>
</div>
And here is the .ts
file for the same component:
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);
})
}
}
I am looking for a solution to display the property of a single user (stored in the database) in the textbox. Any suggestions on how I can achieve this?