我想要的步骤包括:使用以下方法填充和显示从数据库获取的表:-service " DataService“,在方法getPoints()中使用返回的httpClient可观察的-parent组件"Data-import”,使用方法implementTable(),使用来自注入的DataService -child组件" table - with _data“的服务方法getPoints(),我通过@Input属性返回的表Points[],模型: Point{x,y}绑定到该组件。
(我有json-server) *下一个问题是从最后上传的csv文件中获取数据
+我的问题出现在servise的getPoints()方法和我想实现Points[]的implementTable()方法之间。我不知道绑定父子组件值“在普通类型”和“在可观察类型”中有区别。
数据导入组件
export class DataImportComponent implements OnInit {
private points: Point[];
private pointsObservable: Observable<Point[]>;
constructor(private dataService: DataService) {}
implementTable() {
return this.dataService.getPoints().subscribe((data: Point[]) => {
this.pointsObservable = data;
});
}
ngOnInit() {
this.implementTable();
}
}<div class="table">
<br />
<app-table-with-data [point]="point" [points]="points"></app-table-with-data>
</div>数据服务
export class DataService {
baseURL = "http://localhost:3000";
constructor(private http: HttpClient) {}
getPoints(): Observable<Point[]> {
return this.http.get<Point[]>(this.baseURL + "/points");
}
}表组件
export class TableWithDataComponent implements OnInit {
@Input() point: Point;
@Input() points: Observable<Point[]>;
constructor() {}
ngOnInit() {}
}<tbody>
<tr *ngFor="let point of points | async">
<td>{{ point.x }}</td>
<td>{{ point.y }}</td>
</tr>
</tbody>我的另一个问题是:如果我想上传文件并将其保存到服务器,如何让注入到UploaderComponent中的UploaderService工作,因为我想做的下一件事是以表的形式创建这个文件(带数据的表),如上所述。Doest uploadFile和seveToServer方法是两个独立的操作,还是第二个是第一个操作的一部分?下面是我的代码:
export class UploaderService {
baseURL = 'http://localhost:3000';
constructor(private http : HttpClient) {}
public uploadFile( file: File ): Observable<any> {
return this.http.post(this.baseURL+'uploaded', file );
}
constructor( uploaderService: UploaderService ) { }
public uploadFile( file: File ) {
this.uploaderService.uploadFile(file);
}
public postOnServer(file: File){
this.uploaderService.uploadFile(file);
}
<input
#fileInput
type="file"
class="upload__input"
(change)="uploadFile( fileInput.file) ; fileInput.value = null;"
/>
<button (click)="postOnServer(fileInput.file)">Save file</button>我试着用例子来说明这一点,它把我搞糊涂了。
发布于 2019-08-18 23:46:53
您的问题一定是传递了Point[],但是表组件需要一个Observable<Point[]>。
因此,您可以按如下方式更改父组件:
export class DataImportComponent {
public points$: Observable<Point[]>;
constructor(private readonly dataService: DataService) {
this.points$ = this.dataService.getPoints();
}
}<div class="table">
<br />
<app-table-with-data [points]="points$ | async"></app-table-with-data>
</div>在这里,您将在顶级组件订阅points$ observable,并将值向下传递子组件(使它们变得愚蠢)。
因此,表组件可以是:
export class TableWithDataComponent {
@Input() points: Point[];
}<tbody>
<tr *ngFor="let point of points">
<td>{{ point.x }}</td>
<td>{{ point.y }}</td>
</tr>
</tbody>https://stackoverflow.com/questions/57543465
复制相似问题