【问题标题】:How to get data from service into class and send it to the html component如何从服务中获取数据到类中并将其发送到 html 组件
【发布时间】:2022-01-27 02:13:38
【问题描述】:

所以我是 Angular 新手,正在尝试构建一个小项目。

如何从服务中获取数据到类中并发送到 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

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您可以使用async 管道,因为您获得的数据是异步的。您可以像这样使用.html 文件:

    &lt;wrapper[group]="groupData | async"&gt;&lt;/wrapper&gt;

    一个重要的注意事项是async 自动订阅并负责触发您的http 调用。它还会自动取消订阅,因此您无需在组件 .ts 中的 ngOnDestroy 生命周期方法中显式调用 .unsubscribe()

    阅读更多关于它的信息:https://angular.io/api/common/AsyncPipe

    【讨论】:

    • 参数类型字符串不可分配给参数类型 Observable |订阅 |承诺
    • 在 getter 中将返回类型 string 更改为 Observable&lt;string&gt;。我们应该订阅Observable 而不是string
    【解决方案2】:

    公共组:字符串;将其更改为可观察类型

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案3】:

    首先,您永远不应该在 get 方法中向您的 api 发出 get 请求。 (如果所有其他组件都正确编写,则更改这应该可以解决您的问题) 这样,您将无限调用它,直到程序崩溃。 所以不要这样称呼它:

    <wrapper [group]="groupData"></wrapper>
    

    您应该在 ngOnInit 方法或构造函数或任何其他您想要的地方设置数据,但要确保它不是以 get 方式调用的方法。

    其次,你的类不是一个组件。正确编写的组件如下所示:

    @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 类编写正确,您应该会看到 getGroupData() 方法返回的字符串。

    如果这有帮助,请告诉我,如果没有帮助,请写下其他信息(例如,关于 GroupService 类、带有 html 和装饰器的整个组件)

    【讨论】:

    • 顺便说一句。如果您想要实现的只是将服务中的数据获取到您的包装器组件中,而 Groups Class 根本不是一个组件。那你为什么不直接调用 ``` this.groupService.getAll(); ``` 在 WrapperComponent 中?无法通过@Input 将数据从类传递到组件。只能在 html 文件中从一个组件到另一个组件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    相关资源
    最近更新 更多