Angular Вложенный класс - PullRequest
0 голосов
/ 08 июля 2020

Я новичок в angular, но хочу спросить, есть ли способ создать вложенный класс в angular вот так. net class?

public class BaseResponse<T>
{
    public T Data { get; set; }
    public int StatusCode { get; set; }
    public string Message { get; set; }

    public BaseResponse()
    {

    }

    public BaseResponse(T data)
    {
        Data = data;
    }

    public BaseResponse(int statusCode, string message)
    {
        StatusCode = statusCode;
        Message = message;
    }

    public BaseResponse(T data, int statusCode, string message)
    {
        Data = data;
        StatusCode = statusCode;
        Message = message;
    }
}

Когда я использую этот класс и добавьте класс к объекту T, например Раздел класс, вот результат из Backend:

{
"Data": [
    {
        "ID": 3,
        "SectionName": "Section3",
        "Description": "Description3"
    },
    {
        "ID": 4,
        "SectionName": "Section4",
        "Description": "Description4"
    }
],
"StatusCode": 200,
"Message": "Data successfully retrieved"
}

Как получить доступ к этим JSON данным из angular? Я пробую этот код ниже, но не смог.

export class Baseresponse<T> {
    Data:T;
    StatusCode:number;
    Message:string;

    constructor(data:T,statuscode:number,message:string) {
        this.Data=data;
        this.StatusCode=statuscode;
        this.Message=message;
    }
}

это моя служба, но ничего не работает

export class SectionService {
objectResponse:Baseresponse<Section>;
 
constructor(private http:HttpClient) { }

getAllSection(){
  this.http.get(environment.wsURL+'/SectionGetAll').toPromise().then(res=>this.objectResponse=res);
  return this.objectResponse;
}
}

1 Ответ

0 голосов
/ 08 июля 2020

Это из-за асинхронного подхода. Когда вы вызываете this.http.get, он будет поставлен в очередь, а return this.objectResponse вернет undefined для этого момента. Вам нужно сделать что-то вроде этого:

export class SectionService {
  objectResponse: Baseresponse<Section>;

  constructor(private http:HttpClient) { }

  getAllSection(): Promise<Baseresponse<Section>> {
    /* 
      we return Promise object to have ability handle 
      the request or error in a place where we are going to call it 
    */

    return this.http
      .get(environment.wsURL + '/SectionGetAll')
      .toPromise();

    /* 
      if you need a simple cache you can: 

      if (this.objectResponse) { 
        return Promise.resolve(this.objectResponse);
      }

      return this.http
        .get(environment.wsURL + '/SectionGetAll')
        .toPromise()
        .then(response => this.objectResponse = response);
    */
  }
}

Затем где-нибудь в компоненте или другом сервисе:

export class SomeClass {
  /* inject appropriate service */
  constructor(private sectionService: SectionService) {}

  getAll() {
    /* fetch all sections and handle the request */
    this.sectionService.getAllSection()
      .then(response => /* handle response */)
  }
}

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...