【问题标题】:How to call web API return Boolean from angular 7?如何从 Angular 7 调用 Web API 返回布尔值?
【发布时间】:2021-09-02 01:17:57
【问题描述】:

我在 Angular 7 上工作,我遇到了无法从 Angular 7 调用 Web API 返回布尔值的问题

那么如何在 Angular 7 上调用 Web API 返回真或假

   [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 angular-material asp.net-core-webapi angular7 angular-components


    【解决方案1】:

    您需要使用HttpClientModuleAngular

    要使用它,您必须将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 example

    【讨论】:

      【解决方案2】:

      您可以使用@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;
      }
      

      component.html

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

      【讨论】:

      • 等服务怎么写呢
      • 使用我提供的test()函数,用你的url替换'url',尝试从组件调用函数并通过尝试找出它:)
      • 我将我的应用程序分为服务和组件 ts 和组件 html,所以我在服务上写什么,我在组件 ts 上写什么,我在 html 组件上写什么
      • 好吧,我明白了,在 component.ts 上是你所有的逻辑,在 service.ts 上是所有可重用的部分,在 component.html 上是你的显示器。
      • @ahmedbarbary 如果回复解决了您的问题,请将其标记为已解决!
      猜你喜欢
      • 1970-01-01
      • 2019-11-26
      • 2013-05-21
      • 1970-01-01
      • 2016-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多