angular - 我想在指令中调用我的 API 并在需要的地方使用指令。任何人都可以帮助我。请罚款我的例子
问题描述
我正在尝试通过在指令中调用 API 来显示 API 数据,任何人都可以帮助我。
app.component.html
<label>Display Titles</label>
<select class="rounded-inputs20
select-select col-md-3">
<option appDropdown></option>
</select>
dropdown.directive.ts
import {
HttpClient
} from '@angular/common/http';
import {
Directive
} from '@angular/core';
@Directive({
selector: '[appDropdown]'
})
export class DropdownDirective {
displaytitle: any;
constructor(private http: HttpClient) {}
gettitle() {
this.http
.get('https://jsonplaceholder.typicode.com/todos')
.subscribe(data => {
this.displaytitle = data;
console.log('titles', data);
});
}
}
https://stackblitz.com/edit/angular-dropdown-bfrzcs?file=dropdown.directive.ts
解决方案
I really don't like using an HTTP request inside a directive, but here you are the solution.
Directive
import { HttpClient } from '@angular/common/http';
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appDropdown]'
})
export class DropdownDirective {
displaytitle: any;
constructor(
private http: HttpClient,
private el: ElementRef
) {
el.nativeElement.innerHTML = this.gettitle();
}
gettitle() {
this.http
.get('https://jsonplaceholder.typicode.com/todos')
.subscribe(data => {
Object.values(data).forEach((e) => this.el.nativeElement.innerHTML += `<option>${e.title}</otpion>`);
});
}
}
You have to "take" your current element to be able to handle it and write your data. So use ElementRef
.
Component template
<select class="rounded-inputs20 select-select col-md-3" appDropdown>
</select>
In order to write every option, you have to use the directive
in select
推荐阅读
- python - Python 上的每日数据到每月平均值
- qliksense - Qlik 意义上如何停止销售过去 2 年销量不足的产品
- rest - 从 Docusign REST API 读取特定用户 ID 的信封
- r - 将调查数据转换为 R 中的数值数据
- react-native - 图片未显示在 React Native 的个人资料页面上
- ipython - 为什么我不能将 python 变量传递给 jupyter 魔术函数?
- php - 在 Wordpress 中将两个字符串与 strpos 进行比较。非字母字符会导致它失败吗?
- google-cloud-platform - 订阅 PubSub 主题的速率限制/节流谷歌云功能
- html - 如何自动换行标题?
- python-3.x - 如何根据链接中的数字制作 Beautiful Soup 过滤器结果