【问题标题】:How to pass some string or data from API to an angular component in angular 6?如何将一些字符串或数据从 API 传递到角度 6 中的角度组件?
【发布时间】:2020-01-26 12:17:30
【问题描述】:

我从 API 控制器中的 URI 响应中获取字符串。现在我想将此响应(字符串)带到角度内部的某个部分。

string email = jsonResponse.Substring(41, brace - 42);

这是我想带入角度部分的字符串。 Angular 的地址是 localhost:4200,而 localhost:5000 是 API 的地址。

【问题讨论】:

  • 您到底想达到什么目的?要将值绑定到模板吗?
  • 我想把这个字符串从api带到角度组件
  • 您是否在 Angular 应用服务中获取字符串?
  • 我在 .Net API 控制器中得到这个字符串。它在 API 部分而不是在角度部分。

标签: javascript c# angular asp.net-web-api


【解决方案1】:

你可以在这个服务中创建一个你必须添加这个的服务:

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

export class RequestService {
    constructor(public http: HttpClient) {}
    apiUrl : string = "http://localhost:5000";
    getResponse() : Observable<string>{
        return this.http.get<string>(this.apiUrl+"/calledMethod");
    }
}

在您的 app.component.ts 中:

import { RequestService } from './request.service'
import { Component, OnInit } from '@angular/core';

    export class AppComponent implements OnInit{
        stringResult : string = ""

    constructor(private request : RequestService) {}

   ngOnInit()
   {
        this.showResponse()
   }

    showResponse(){
        this.request.getResponse().subscribe(
            r => this.stringResult = r,
            err => console.log(err)
        )
    }
}

在您的 app.component.html 中完成:

{{stringResult}}

示例: API request

【讨论】:

  • 没关系!但是由于我在 API 中,如何从 API 方法触发这个 getResponce()??
  • @HurAbbas 你在 API 中吗?我不明白。
  • @HurAbbas 你想在你的 api 中创建一个方法,然后在 angular 中调用它?
  • 我得到这个字符串以响应一个名为 URI 的重定向 url 是 localhost:5000,因此在获取响应后,我在 api 中,现在我想把这个结果带到 angular部分。
  • 然后按照服务从你的api调用你的方法的步骤来获取响应,组件将字符串放入一个变量中,你的html显示变量的内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-14
  • 2019-02-11
  • 2018-07-08
  • 1970-01-01
  • 2019-07-02
  • 2019-08-03
相关资源
最近更新 更多