繁体   English   中英

如何将一些字符串或数据从 API 传递到 angular 6 中的 angular 组件?

[英]How to pass some string or data from API to an angular component in angular 6?

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

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

这是我想带到 angular 部分的字符串。 angular 的地址是 localhost:4200,而 localhost:5000 是 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 请求

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM