【问题标题】:What is a correct way to insert a service variable into component of Angular将服务变量插入Angular组件的正确方法是什么
【发布时间】:2019-12-20 21:41:21
【问题描述】:

在组件的模板中使用服务变量(如下面的代码)是个好主意吗? 问题是,当我尝试像这样在组件本身中定义这个变量时:usersList = this.service.arr,然后在这样的模板中使用:ngFor = let item of usersList。 如果没有一些额外的步骤,它就无法工作 - 例如,使用 Subject 。

@Injectable()
export class SomeService {
    arr: SomeObject[];

    constructor(private http: HttpClient) { }

    getUsers() {
        this.http.get('someUrl')
            .subscribe(
                res => arr as SomeObject[])
    };
}

@Component({
    selector: 'app-smth',
    templateUrl: template: `
    <ul *ngFor = "let item of service.arr">
    <li>Name: {{item.name}}</li>
  </ul>  `
})

export class CategoryComponent implements OnInit, OnChanges {
    constructor(private service: SomeService) { }

【问题讨论】:

  • service.arrnever 在您的示例中除了 undefined 之外的任何东西,您的订阅实际上并未分配给它。如果该值一开始不可用,则公开一个 observable
  • o.因为这是我的错误。它应该是这样的: res => res = arr as SomeObject[]。它以正确的方式工作。

标签: angular typescript


【解决方案1】:

您应该从服务返回一个 Observable 并订阅组件或在组件的模板中使用 async 管道。

async 管道示例

服务:

@Injectable()
export class SomeService {

    constructor(private http: HttpClient) { }

    getUsers(): Observable<SomeObj[]> {
        return this.http.get('someUrl');
    }
}

组件:

@Component({
    selector: 'app-smth',
    templateUrl: template: `
    <ul *ngFor = "let item of data$ | async">
    <li>Name: {{item.name}}</li>
  </ul>`
})
export class CategoryComponent implements OnInit, OnChanges {
    data$: Observable<SomeObj[]> = this.service.getUsers();

    constructor(private service: SomeService) { }
}

【讨论】:

    猜你喜欢
    • 2020-01-21
    • 2017-10-30
    • 1970-01-01
    • 2014-06-14
    • 2012-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多