在Angular 2/4中,可以使用服务层中的Promise函数来获取数组值,并将其分配给组件中的变量。下面是一个示例解决方案:
在服务层中,创建一个返回Promise函数的方法,用于获取数组值。例如:
import { Injectable } from '@angular/core';
@Injectable()
export class MyService {
getArrayValues(): Promise {
return new Promise((resolve, reject) => {
// 模拟异步获取数组值
setTimeout(() => {
resolve([1, 2, 3, 4, 5]); // 假设这是从服务获取的数组值
}, 2000);
});
}
}
在组件中,使用服务层的方法来获取数组值,并将其分配给组件的变量。例如:
import { Component, OnInit } from '@angular/core';
import { MyService } from './my.service';
@Component({
selector: 'app-my-component',
templateUrl: './my.component.html',
styleUrls: ['./my.component.css']
})
export class MyComponent implements OnInit {
myArray: any[];
constructor(private myService: MyService) { }
ngOnInit() {
this.myService.getArrayValues()
.then((values) => {
this.myArray = values;
})
.catch((error) => {
console.error('Error:', error);
});
}
}
在组件的HTML模板中,可以使用*ngFor
指令来循环遍历数组,并显示其值。例如:
- {{ value }}
通过上述代码示例,你可以在Angular 2/4中将服务层中的Promise函数的数组值分配给组件中的变量。