要将从 SQL 返回的列表复制到数组中,您可以使用Angular的HttpClient模块来执行SQL查询并获取结果。然后,您可以使用Array的slice方法将结果复制到新的数组中。
以下是一个示例解决方案:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
getSQLData(): Promise {
const url = 'your_sql_api_url'; // 替换为您的SQL API URL
return this.http.get(url).toPromise();
}
}
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
sqlData: any[];
constructor(private dataService: DataService) { }
ngOnInit(): void {
this.dataService.getSQLData().then(data => {
this.sqlData = data.slice(); // 复制数据到新的数组中
}).catch(error => {
console.error(error);
});
}
}
{{ item.propertyName }}
请确保将data.service.ts添加到提供者列表中,并将HttpClientModule导入到你的应用程序的根模块中(通常是app.module.ts)。
这样,当组件初始化时,它将调用数据服务来获取SQL数据并将其复制到数组中。然后,您可以在模板中使用 *ngFor 指令来显示数组的内容。