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

问题描述

大家好,我正在尝试从 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 时,它​​不能在范围之外被引用(您只能在 {} 内引用 result a 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,}


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