I've been following a course on LinkedIn Learning but clicking on a list and having the values populate a form are not working for me. I'm new to Angular (and development) so apologies if this is silly, or I don't describe it correctly.
I have 2 components and an API service file pulling the data from an ASP.Net Core API:
list-codes.component.html
<div class="card-body">
<p class="card-text">select a code from the list below.</p>
<ul class="list-group" *ngFor="let code of codes">
<a href="#" class="list-group-item list-group-item-action" (click)="api.selectCode(code)">{{code.codeName}}</a>
</ul>
</div>
list-codes.component.ts
ngOnInit() {
this.api.getCodes().subscribe(res => {
this.codes = res
})
}
add-code.component.html
<form>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="">:)</span>
</div>
<input type="text" class="form-control" [(ngModel)]="code.codename" name="codename" placeholder="code name">
<input type="text" class="form-control" [(ngModel)]="code.description" name="description" placeholder="description">
</div>
<button (click)="post(code)" class="btn btn-primary">Submit</button>
</form>
add-code.component.ts
export class AddCodeComponent {
code = {}
constructor(private api: ApiService) {}
ngOnit() {
this.api.codeSelected.subscribe(code => this.code = code)
}
post(code) {
this.api.postCode(code)
}
}
api.service.ts
export class ApiService {
private selectedCode = new Subject<any>(); // holds reference to clicked item in list
codeSelected= this.selectedCode.asObservable(); // subscribe
constructor(private http: HttpClient) {}
getCodes() {
return this.http.get('http://localhost:58561/api/codes');
}
postCode(code) {
this.http.post('http://localhost:58561/api/codes', code).subscribe(res => {
console.log(res)
})
}
selectCode(code) {
this.selectedCode.next(code)
}
}
Listing the codes works fine.
The issue just seems to be clicking and having the code in the list populate the values in the add-code form (it works in the video tutorial) but it doesn't work for me. I'm assuming I've missed something obvious?
I did a bit of reading and everyone seems to handle Subject Observables slightly different and I"m obviously just missing the point!
For brevity, I've provided the snippets I think are relevant. If I've overlooked something important to include please let me know.
Any help welcomed!
Cheers, Adam
In your list-codes.component.ts
you only subscribe to the observable returned by your api.service.getCodes()
once because an Observable is Cold by default and thus when it completes you automatically unsubscribe.
In order for your form to keep updating you need to implement something that will keep calling your service.getCodes().subscribe(blah)
to fetch new data.