[英]How to bind selected/option value to get request function in service.ts and not component.ts (Angular 8)
我需要有關如何獲取選定值並將其連接到“ service.ts”內部的url上的幫助,然后使用將該URL放置在component.ts中的函數。 我知道如何將數據從component.html綁定到component.ts,但是我想知道的是綁定到service.ts。 請參閱下面的代碼:
component.html
<select class="browser-default custom-select" [(ngModel)]="bindSelect">
<option value="" selected disabled>Choose item</option>
<option [value]="mydata.name" *ngFor="let mydata of vList$">
<td>{{ mydata.id }} - {{ mydata.name }}</td>
</option>
</select>
服務
export class ItenService {
constructor(private http: HttpClient) { }
myUrl = 'http://localhost:4045/store/itemList';
valueFromSelect = '';
getData() {
return this.http.get<itemData[]>('http://localhost:4045/store/itemList/' + this.valueFromSelect);
}
}
component.ts
export class ItemComponent implements OnInit {
vList$ = [];
bindSelect = '';
constructor(private idataService: IdataService) { }
ngOnInit() {
this.getImpl();
}
getImpl() {
// impl service.ts function here
}
}
如何將.html中的“ valueFromSelect”從.html綁定到service.ts,以便當我選擇項目時,值綁定到valueFromSelect ='';
謝謝
您無法將.html
直接綁定到服務實例。 這可以通過您的component.ts
因此,方法是將service.ts-component.ts-html綁定在一起。 請參見下面的代碼段。
.html
<select class="browser-default custom-select" [(ngModel)]="valueFromSelect" (change)="onSelect()">
<option value="" selected disabled>Choose item</option>
<option [value]="mydata.name" *ngFor="let mydata of vList">
<td>{{ mydata.id }} - {{ mydata.name }}</td>
</option>
</select>
.component.ts
import { Component, OnInit } from '@angular/core';
import { SampleService } from './app.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
vList;
valueFromSelect;
constructor(private sampleService: SampleService) { }
ngOnInit() {
// gets from service
this.vList = this.sampleService.vList;
}
onSelect() {
console.log(this.valueFromSelect);
// sets to the service
this.sampleService.valueFromSelect = this.valueFromSelect;
}
}
.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class SampleService {
vList = [{
id: 1,
name: 'Bob'
}];
valueFromSelect;
constructor() { }
}
實際上,您需要將component.TS中的代碼更改為此。 當下拉列表中的選擇更改時,調用函數getImpl()。
component.ts
export class ItemComponent implements OnInit {
vList$ = [];
bindSelect = '';
constructor(private idataService: IdataService,private ItenService: ITenService) { }
ngOnInit() {
this.getImpl();
}
getImpl() {
this.ItenService.valueFromSelect = this.bindSelect;
// impl service.ts function here
this.ItenService.getData();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.