首页 > 解决方案 > 如何将一些字符串或数据从 API 传递到角度 6 中的角度组件?

问题描述

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

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

这是我想带到角度部分的字符串。角度的地址是 localhost:4200 和 localhost:5000 用于 API。

标签: javascriptc#angularasp.net-web-api

解决方案


您可以在此服务中创建一个服务,您必须添加以下内容:

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 请求


推荐阅读