{{ getData() }}..."> {{ getData() }}..."/> {{ getData() }}..."> {{ getData() }}...">

angular 2如何从订阅返回数据

JavaScript TypeScript

十三西门

2020-05-28

这就是我想做的。

@Component({
   selector: "data",
   template: "<h1>{{ getData() }}</h1>"
})

export class DataComponent{
    this.http.get(path).subscribe({
       res => return res;
    })
}

如果getData在中被调用DataComponent,您可能会建议将其分配给变量like this.data = res并使用i like {{data}}。但是{{getData}}出于个人目的,我需要使用like 。请提出建议?

第4199篇《angular 2如何从订阅返回数据》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
王者一打九银 2020.05.28

我知道两种方法:

export class SomeComponent implements OnInit
{
    public localVar:any;

    ngOnInit(){
        this.http.get(Path).map(res => res.json()).subscribe(res => this.localVar = res);
    }
}

一旦像承诺中那样返回信息,这会将您的结果分配给局部变量。那你就做{{ localVar }}

另一种方法是获取一个可观察值作为localVariable。

export class SomeComponent
{
    public localVar:any;

    constructor()
    {
        this.localVar = this.http.get(path).map(res => res.json());
    }
}

通过这种方式,您可以在html中公开一个可观察对象,即使用AsyncPipe {{ localVar | async }}

请尝试一下,让我知道它是否有效。另外,由于角度2非常新,如果出现问题,请随时发表评论。

希望能帮助到你

伊芙妮 2020.05.28

我已经用这种方式很多时间了...

@Component({
   selector: "data",
   template: "<h1>{{ getData() }}</h1>"
})

export class DataComponent{
    this.http.get(path).subscribe({
       DataComponent.setSubscribeData(res);
    })
}


static subscribeData:any;
static setSubscribeData(data):any{
    DataComponent.subscribeData=data;
    return data;
}

use static keyword and save your time... here either you can use static variable or directly return object you want.... hope it will help you.. happy coding...

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android