[英]In Angular2, How do I send from JSON from service/component to my HTML component?
[英]How to get data from service into class and send it to the html component
所以我是 angular 的新手,並試圖建立一個小項目。
如何從服務中獲取數據到 class 並將其發送到 html 組件?
// service.groups.ts
export class GroupService {
public getAll(): void {
return // httpService call...works!
}
}
// groups.class.ts
import {GroupService} from '@core/services/group/group.service';
export class {
protected constructor(private groupService: GroupService);
public get groupData(): string {
let data = this.groupService.getAll();
// some extra filtering comes here
return data;
}
}
// wrapper.component.html
<wrapper[group]="groupData"></wrapper>
// wrapper.component.ts
export class WrapperComponent {
@Input()
public group: string;
}
// wrapper.html
<div>{{ group }}</div>//not working
您可以使用async
pipe 因為您獲得的數據是異步的。 您可以像這樣使用.html
文件:
<wrapper[group]="groupData | async"></wrapper>
一個重要的注意事項是async
訂閱自動並負責觸發您的 http 調用。 此外,它會自動取消訂閱,因此您無需在組件.ts
的ngOnDestroy
生命周期方法中顯式調用.unsubscribe()
。
閱讀更多關於它的信息: https://angular.io/api/common/AsyncPipe
首先,您永遠不應該在 get 方法中向您的 api 發出 get 請求。 (如果所有其他組件都正確編寫,則更改這應該可以解決您的問題)這樣您將無限調用它,直到程序崩潰。 所以不要這樣稱呼它:
<wrapper [group]="groupData"></wrapper>
您應該在 ngOnInit 方法或構造函數或您想要的任何其他地方設置數據,但要確保它不是以 get 方式調用的方法。
其次,您的 class 不是組件。 正確編寫的組件如下所示:
@Component({
selector: 'app-some-component',
templateUrl: 'some.component.html',
styleUrls: ['some.component.scss']
})
export class SomeComponent implements OnInit {
groupData: string = "";
constructor(private groupService: GroupService) {
}
ngOnInit() {
groupData = getGroupData();
}
public getGroupData(): string {
return this.groupService.getAll();
}
}
請注意,這里有組件裝飾器。 Selector 和 styleUrls 不是必需的,但在大多數情況下您仍會使用它。 TemplateUrl 可以替換為模板。
同樣,第二個組件缺少“@Component”裝飾器。
現在如果你添加
<wrapper [group]="groupData"></wrapper>
在 some.component.html 中,如果 GroupService class 正確寫入,您應該會看到 getGroupData() 方法返回的字符串。
讓我知道這是否有幫助,如果沒有幫助,請寫下其他信息(例如,關於 GroupService class、帶有 html 和裝飾器的整個組件)
公共組:字符串; 將其更改為可觀察類型
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.