簡體   English   中英

如何從 angular 7 調用 Web API 返回布爾值?

[英]How to call web API return Boolean from angular 7?

我在 angular 7 上工作我遇到了問題我無法從 angular 7 調用 web API return Boolean

那么如何在 angular 7 上調用 Web API 返回 true 或 false

   [HttpGet]
    [Route("CompareExcel/SelectedOptions")]
    public IActionResult CompareExcel( int SelectedOptions)
    {
        var DisplayFileName = Request.Form.Files[0];
        string fileName = DisplayFileName.FileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";
        string Month = DateTime.Now.Month.ToString();
        string DirectoryCreate = Path.Combine(myValue1, Month);// myValue1 + "\\" + Month + "\\" + fileName;
        CExcel ex = new CExcel();
    
        string error = "";
        int rowCount = 0;
        var selectedFile = "";
        var filedata = ContentDispositionHeaderValue.Parse(Request.Form.Files[0].ContentDisposition).FileName.Trim('"');
        var dbPath = Path.Combine(DirectoryCreate, fileName);
        if (SelectedOptions == 1)
        {
            selectedFile = "Gen.xlsx";
        }
        else if(SelectedOptions == 2)
        {
            selectedFile = "DeliveryGeneration_Input.xlsx";
        }
        var InputfilePath = System.IO.Path.Combine(GetFilesDownload, selectedFile);
        using (var stream = new FileStream(dbPath, FileMode.Create))
        {
            Request.Form.Files[0].CopyTo(stream);
            stream.Flush();
            stream.Close();
        }
        GC.Collect();
        bool areIdentical = ex.CompareExcel(dbPath, InputfilePath, out rowCount, out error);
        if(areIdentical==true)
        {
            return Ok(true);
        
        }
        else
        {
            return Ok(false);
            
        }
    
    }

用於從 angular 調用 Web API 的鏈接

http://localhost:61265/api/DeliverySys/CompareExcel/SelectedOptions?=1

當調用上面的函數時,它只返回布爾值 true 或 false

如果比較excel相同則返回true

如果比較 excel 不相同則返回 false

so on angular service.ts
//what I write 
component Type script ts
what I write
html component
what I write 

更新帖子

on service ts i do as below :
CompareExcel(SelectedOptions)
{
  this.http.get('http://localhost:61265/api/DeliverySys/CompareExcel/SelectedOptions?=' + SelectedOptions).subscribe(result => {
    console.log(result);
});
}
on component ts
i call it as 

  this._dataService.CompareExcel(this.selectedoptions.toString())
so are this correct 

on component html 
what i write 

您可以使用@angular/core模塊Http調用網絡路由。

像這樣導入:

import { HttpClient } from '@angular/common/http';

像這樣使用:

constructor(
    private http: HttpClient
) { }

test () {
    // with observable
    this.http.get('url').subscribe(result => {
        console.log(result);
    });

    // with promise
    this.http.get('url').toPromise().then(result => {
        console.log(result);
    });
}

不要忘記在app.module.ts添加:

import { HttpClientModule } from '@angular/common/http';

// add it in your imports
@NgModule ({
    declarations: [],
    imports: [
        HttpClientModule
    ]
})

在您的情況下,您希望執行以下操作

組件.ts

import { YourService } from 'path/to/service';

...

constructor(
    private yourService: YourService,
) { }

...

async ngOnInit() {
    const result = await this.yourService.callMyFunction();
    console.log(result);
}

yourService.ts

async callMyFunction() {
    const result = await this.http.get(yourUrl);
    return result;
}

組件.html

<p>{{result}}</p>

您需要使用Angular HttpClientModule

要使用它,您必須將HttpClientModule導入到您的根模塊中。

app.module.ts 或 core.module.ts

@NgModule({
  imports: [..., HttpClientModule]
})
export class AppModule {} 

其次,您可以創建一個服務來處理請求背后的邏輯。

foo.service.ts

@Injectable({
  providedIn: 'root'
})
export class FooService {
  constructor(private http: HttpClient) {}

  get(): Observable<boolean> {
    return this.http.get<boolean>(<url>);
  }
}

在代碼中可以看到, HttpClient方法是通用的,因此通過使用它,我們可以管理 API 響應具有布爾類型。

最后,您可以在組件中使用您的服務,如下所示;

constructor(private service: FooService) {}

  get(): void {
    this.service.get().subscribe(resp => {
      if (resp) {
        console.log('yayyy');
      } else {
        console.log('nooo');
      }
    });
  }

我為您創建了一個stackblitz 示例

暫無
暫無

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

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