如何从 angular 中的 url 获取数据并将其保存在变量中

how to fetch data from a url in angular and save it in a variable

大家好,我正在尝试从 URL 中获取数据并将该数据保存在一个变量中,我需要该变量及其值。

这是我的服务。

import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse} from "@angular/common/http";



const route: string = "http://localhost:51044/api/";

export enum userActions{
  signin,
  signup,
}


interface DataResponse {
  result: boolean;
  accessCode: string;
}

@Injectable({
  providedIn: 'root'
})
export class TaskPlusPlusControllerService {



  constructor(private http: HttpClient) {
  }


  public FetchData(properties: string, action: userActions)
  {
    switch (action)
    {
      case userActions.signin:
        this.getListOfGroup('signin/' + properties);
      break;
      case userActions.signup:
        break;
    }
  }


  private getListOfGroup(url: string) {
    let fetchedData: DataResponse = {result: null,accessCode: ''};
    this.http.get(route + url).subscribe(
      (res) => {
        console.log(res);
        console.log(res['result']);
        console.log(res['accessCode']);
        //fetchedData = res;
        fetchedData.result = res['result'];
        fetchedData.accessCode = res['accessCode'];
      }
    );
    console.log(fetchedData);
  }
}

所以我直接从 res 获取控制台中的数据,但是当我登录时 fetchedData 它的值没有改变。

我该怎么做?

javascript 是一种异步编程语言。您必须在订阅方法中执行 console.log 操作。


private getListOfGroup(url: string) {
    let fetchedData: DataResponse = {result: null,accessCode: ''};
    this.http.get(route + url).subscribe(
      (res) => {
        console.log(res);
        console.log(res['result']);
        console.log(res['accessCode']);
        //fetchedData = res;
        fetchedData.result = res['result'];
        fetchedData.accessCode = res['accessCode'];

        // move here
        console.log(fetchedData);
      }
    );
   // remove from here
   console.log(fetchedData);
  }

Javascript是单线程的异步语言。当您调用 promise 时,它​​不能在范围外引用(您只能在 {} 内引用 promise 结果的值)。 如果你想使用 fetchedData 作为另一个功能。试试这个:

import {Injectable} from '@angular/core';
    import {HttpClient, HttpErrorResponse} from "@angular/common/http";
    
    
    
    const route: string = "http://localhost:51044/api/";
    
    export enum userActions{
      signin,
      signup,
    }
    
    
    interface DataResponse {
      result: boolean;
      accessCode: string;
    }
    
    @Injectable({
      providedIn: 'root'
    })
    export class TaskPlusPlusControllerService {
    
      fetchedData: DataResponse = null;
    
      constructor(private http: HttpClient) {
          this.fetchedData = {result: null,accessCode: ''};
      }
    
    
      public FetchData(properties: string, action: userActions)
      {
        switch (action)
        {
          case userActions.signin:
            this.getListOfGroup('signin/' + properties);
          break;
          case userActions.signup:
            break;
        }
      }
    
    
      private getListOfGroup(url: string) {
        let fetchedData: DataResponse = {result: null,accessCode: ''};
        this.http.get(route + url).subscribe(
          (res) => {
            console.log(res);
            console.log(res['result']);
            console.log(res['accessCode']);
            //fetchedData = res;
            this.fetchedData.result = res['result'];
            this.fetchedData.accessCode = res['accessCode'];
          }
        );
      }
    }
import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";



const route: string = "http://localhost:51044/api/";

export enum userActions{
  signin,
  signup,
}


@Injectable({
  providedIn: 'root'
})
export class TaskPlusPlusControllerService {

  blockedPhoneNumbers: string[] = [];
  fetchedData = null;

  constructor(private http: HttpClient) {
  }


/*
  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.log("An error occurred:", error.error.message);
    } else {
      // The backend returned an unsuccessful response code. The response body may contain clues as to what went wrong,
      console.log(
        `Backend returned code ${error.status}, ` + `body was: ${error.error}`
      );
    }
    // return an observable with a user-facing error message
    return throwError(error);
  }

  private extractData(res: Response) {
    return res || {};
  }

*/
  public FetchData(properties: string, action: userActions) {
    switch (action) {
      case userActions.signin:
        /* if (this.blockedPhoneNumbers.length != 0) {
           return this.getListOfGroup('signin/' + properties);
         } else {
           for (let item in this.blockedPhoneNumbers) {
             if (item == properties) {
               return null;
             }
           }
           return this.getListOfGroup('signin/' + properties);
         }*/
        return this.getListOfGroup('signin/' + properties);
        break;
      case userActions.signup:
        break;
    }
  }


  private async getListOfGroup(url: string) {
    this.fetchedData = await this.http.get(route + url).toPromise();
    return this.fetchedData;
  }
}

这里是答案 顺便说一句,现在我可以像这样在组件中的服务之外获取我的数据

this.data = this.taskPlusPlusAPI.FetchData(this.phoneNumber,userActions.signin);
     this.data.then(value => {
       console.log(value);
     })