簡體   English   中英

將 API 響應作為 JSON 從 C# 返回到 Angular

[英]Returning an API response as JSON from C# to angular

["

        [HttpGet("getEmployees")]
        [ProducesResponseType(200, Type = typeof(IEnumerable<EmployeesView>))]
        public async Task<IActionResult> GetEmployeesByCreateDate(DateTime period)
        {
        
            try
            {
                // read model returns users by a logic as enumerable  
                return Ok(await _readModel.GetEmployees(period));
            }
            catch (Exception e)
            {
                // throw exception
            }

subscribe()的返回值是一個Subscription ,用於稍后取消訂閱。 subscribe()不會返回您的數據,它會保存您的回調函數以供以后執行,一旦它收到響應。 取消訂閱一個簡單的 http 請求是不必要的,因為它會在第一次響應后完成。

你可以在回調函數中做任何你想做的事情,或者你可以使用asyncawaitfirstValueFrom()來獲得更多同步的代碼。

此外,您不需要解析它,這是通過HttpClient服務自動完成的。

async getAllPosts(): Promise<IEmployee[]> {
    return await firstValueFrom(this.http.get<IEmployee[]>(this.URL));
}
JsonData = await this.URL.getAllPosts();

或者

getAllPosts(): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.URL);
}
this.URL.getAllPosts().subscribe((data) => JsonData = data);

在您進行編輯后,此解決方案應該適合您:

為您服務

async getAllPosts(): Promise<IEmployee[]> {
    return await firstValueFrom(this.http.get<IEmployee[]>(this.URL));
}

在您的組件中

async download2() { 
  this.URL.download(await this.URL.getAllPosts(), 'jsontocsv'); 
}

我發現您的下載功能存在另一個問題,您有:

let csvData = this.ConvertToCSV(data, ['name1','name2'])

什么時候應該:

let csvData = this.ConvertToCSV(data, ['name', 'surname']);

要使用回調而不是 Promise 來實現:

為您服務

getAllPosts(): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.URL);
}

在您的組件中

download2() { 
  this.URL.getAllPosts().subscribe((data) => this.URL.download(data, 'jsontocsv')); 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM