【问题标题】:Access variable from another function Angular - Get & Post [duplicate]从另一个函数Angular访问变量-获取和发布[重复]
【发布时间】:2021-11-24 02:54:58
【问题描述】:

我正在写一些帖子并获取在 Angular 中访问 API 的请求。 在我的发布请求中,我创建了一个新项目并获取该项目的 ID。 然后编写获取请求以获取该项目,我需要将项目 ID 附加到 url。

如何从get请求中的post请求中获取id?

我创建了变量id,它在createItem() 中被覆盖,并且可以通过简单地编写{{id}} 在HTML 中访问。但是我无法从getItem() 内部的createItem() 访问被覆盖的内容;变量id 保持为空。

到目前为止我的代码:

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/x-www-form-urlencoded',
    Authorization: '...',
  }),
};

type CreatedItem = {id: string; inventory: []}

@Component({
  selector: 'home-component',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent {
  url = 'url here';
  id="";

  constructor(private httpClient: HttpClient) {}

  ngOnInit(): void {
    this.createItem();
    this.getItem();
  }

  createItem() {
    this.httpClient.post(this.url, null, httpOptions).subscribe((res) => {
      const data = res;
      this.id = (data as CreatedItem).id;
    });
  }

  getItem() {
    this.httpClient
      .get<any>(
        this.url + this.id,
        httpOptions
      )
      .subscribe((res) => {
        const data = res;
      });
  }

【问题讨论】:

  • 在您尝试获取项目之前,您的代码中没有任何内容可以确保创建已完成。从方法中公开可观察对象,而不仅仅是在本地订阅它们,否则您获取的数据实际上无法在其他任何地方使用。
  • 抱歉,您能再解释一下吗?我真的没有 Angular 方面的经验,也找不到任何关于这方面的信息。
  • 这不是一个真正的 Angular 甚至 RxJS 特定的问题,例如阅读stackoverflow.com/questions/14220321/….

标签: javascript angular typescript api variables


【解决方案1】:

getItem() 的订阅不知道 createItem() 的订阅是否已完成,这将导致 getItem() 触发时 id 为空。丑陋的解决方法是仅在 createItem() 的订阅完成并且有一个 id 后才调用 getItem():

ngOnInit(): void {
        this.createItem();
    }

    createItem() {
        this.httpClient.post(this.url, null, httpOptions).subscribe((res) => {
            const data = res;
            this.id = (data as CreatedItem).id;
            this.getItem(this.id)
        });
    }

    getItem(id: string) {
        this.httpClient
            .get<any>(
                this.url + id,
                httpOptions
            )
            .subscribe((res) => {
                const data = res;
            });
    }

更好的方法是使用 rxjs switchmap

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多