【问题标题】:How to dynamically load ion-options from array?如何从数组中动态加载离子选项?
【发布时间】:2019-01-09 16:30:25
【问题描述】:

我有一个加载和保存模板的服务,我希望当我点击离子选择时,选项会动态加载,这样每个保存的模板都是一个选项,而不是硬编码的选项。

我尝试使用 NgFor 并创建一个服务实例来处理 JS 文件中的模板。

这是HTML代码

```
<ion-item>
    <ion-label>Load template</ion-label>
        <ion-select>
            <ion-option *ngFor = "let template of templates;">
                {{templates}}
            </ion-option>
        </ion-select>
</ion-item>
```

这是模板服务代码

```
export class TemplateService {
    public templates: Template[] = [];
...
getAllTemplates(): Template[] {
    return this.templates;
}
```

这是 JS 代码

```
export class NewTransactionPage {
    templates: Template[];
...
constructor(public templateServicerino: TemplateService) {
    this.templates = this.templateServicerino.getAllTemplates();
```

我收到一条错误消息:“未捕获(承诺中):错误:StaticInjectorError(AppModule)[NewTransactionPage -> TemplateService: StaticInjectorError(Platform:core)[NewTransactionPage -> TemplateService: NullInjectorError: No provider for Template Service!”

【问题讨论】:

  • 您的代码中有错字,它是*ngFor 而不是ngfor.
  • 您似乎忘记在 app.module 中声明 TemplateService,或者可能是 TemplateServices 自己的依赖项之一

标签: javascript angular ionic-framework ionic3


【解决方案1】:

将服务声明为提供者。一种方法是使用这样的注释。

@Injectable({
  providedIn: 'root'
})

export class TemplateService {//body}

【讨论】:

  • 谢谢您,解决了服务问题,但是我有一些不清楚的地方,我从网上复制了这个格式 。在我的 JS 文件和 HTML 文件中都没有名为“模板”的变量,那是“模板的模板”只是约定吗?我见过的其他例子就像“汽车之车”
  • let template of templates,表示你定义了templatelet template类似于var templateof 关键字一次从 templates 数组获取一项到 template 变量,循环重复直到所有项完成。
猜你喜欢
  • 1970-01-01
  • 2020-05-13
  • 1970-01-01
  • 2018-07-30
  • 1970-01-01
  • 2018-05-29
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多