typescript angular 2如何从用户返回数据

tsm1rwdh  于 2022-11-26  发布在  TypeScript
关注(0)|答案(5)|浏览(101)

这就是我想做的。

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

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

如果getDataDataComponent内部被调用,你可以建议把它赋值给一个变量,比如this.data = res,然后像{{data}}那样使用i。但是我需要像{{getData}}那样使用,以满足我自己的需要。请给我建议?

dgiusagp

dgiusagp1#

你不能直接返回值,因为它是一个异步调用,异步调用意味着它在后台运行(实际上是安排在稍后执行),而你的代码继续执行。
你也不能直接在类中有这样的代码,它需要被移动到一个方法或构造函数中。
您可以做的不是直接使用subscribe(),而是使用map()这样的运算符

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

此外,您可以将多个.map与相同的Observable组合在一起,因为有时候这样可以提高代码的清晰度,并保持代码的独立性。

validateResponse = (response) => validate(response);

parseJson = (json) => JSON.parse(json);

fetchUnits() {
    return this.http.get(requestUrl).map(this.validateResponse).map(this.parseJson);
}

通过这种方式,将返回调用者可以订阅的可观察结果

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

    otherMethod() {
      this.someMethod().subscribe(data => this.data = data);
    }
}

调用者也可以在另一个类中,这里只是为了简洁。

data => this.data = data

res => return res.json()

是箭头函数。它们类似于普通函数。这些函数被传递给subscribe(...)map(...),以便在响应数据到达时从可观察对象调用。这就是为什么数据不能直接返回的原因,因为当someMethod()完成时,数据还没有收到。

hujrc8aj

hujrc8aj2#

我知道有两种方法:

export class SomeComponent implements OnInit
{
    public localVar:any;

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

这会在返回信息后将结果赋给局部变量,就像在promise中一样。
另一种方法是获取一个observable作为localVariable。

export class SomeComponent
{
    public localVar:any;

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

这样你就公开了一个可观察的点,在这个点上你可以在html中使用AsyncPipe{{ localVar | async }}
请试用一下,让我知道它是否有效。另外,由于angular 2是相当新的,如果有什么不对劲,请随时评论。
希望能有所帮助

dgtucam1

dgtucam13#

将这个变量存储在一个可以在subscribe之外使用的变量中怎么样?

this.bindPlusService.getJSONCurrentRequestData(submission).map(data => {
    return delete JSON.parse(data)['$id'];
});
nnvyjq4y

nnvyjq4y4#

使用pipe运算符&订阅getData()或在模板中使用异步管道,如..

template.html
  <h1>{{ data$ | async }}</h1>

  component.ts
  data$ =  this.apiService.getData();

  api.service.ts
  getData() {
      return this._http
        .get(url)
        .pipe(
          map((res: any) => {
           return res;
            // or if you want to transform data
            // return transformRes(res);
        })
      );
   }

   transformRes(res) {return ...transform logic.}
dauxcl2d

dauxcl2d5#

我已经用过很多次了...

@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;
}

使用静态关键字,保存你的时间...这里你可以使用静态变量或直接返回你想要的对象...希望它会帮助你...快乐编码...

相关问题