首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从http请求Angular7获得结果

从http请求Angular7获得结果
EN

Stack Overflow用户
提问于 2019-03-29 03:18:11
回答 1查看 1.2K关注 0票数 2

完全失去理智了。我很困惑。我的目标是从后端服务器获得回复。下面是它的工作原理: GET http://localhost:12345/createUser.php?name=John&age=40返回给我这个json:

代码语言:javascript
复制
{
    "id":"91",
    "name":"John",
    "age":40,
    "birthday":"null"
}

我想通过角发送这个get请求并显示对页面的回复。我只需要身份证和名字。所以,我创建了模型:

代码语言:javascript
复制
export class User {
    id:string;
    name:string;
}

并试图得到回复。下面是我的两个tryes: 1. app.component.ts中的代码:

代码语言:javascript
复制
export class AppComponent implements onInit{ 
  user:User; 

  constructor(private http:HttpClient) { }

  createUser(){
    this.user = this.http.get("http://localhost:12345/createUser.php?name=test&age=20"); 
  }
}

并在app.component.html中创建按钮和文本div来显示它:

代码语言:javascript
复制
<button (click)="createUser()">Create test user!</button> 
<div ><h2>{{user.id}} {{user.name}} </h2></div>

还有..。这里没有结果。但是,如果我将html代码编码为“{user\json}”,则会得到一些答复,但它只是请求信息,如下所示:

代码语言:javascript
复制
{ "_isScalar": false, "source": { "_isScalar": false, "source": { "_isScalar": false, "source": { "_isScalar": true, "value": { "url": "http://localhost:12345/createUser.php?name=John&age=40", "body": null, "reportProgress": false, "withCredentials": false, "responseType": "json", "method": "GET", "headers": { "normalizedNames": {}, "lazyUpdate": null, "headers": {} }, "params": { "updates": null, "cloneFrom": null, "encoder": {}, "map": null }, "urlWithParams": "http://localhost:12345/createUser.php?name=John&age=40" } }, "operator": { "concurrent": 1 } }, "operator": {} }, "operator": {} } 
  1. 第二个尝试是创建数据服务。所以这是我的服务:
代码语言:javascript
复制
export class DataService {

  apiUrl="http://localhost:12345/createUser.php?name=John&age=40";
  constructor(private http:HttpClient) { }

  public createUser()
  {
    return this.http.get<User>(this.apiUrl);
  }
}

和app.component:

代码语言:javascript
复制
user:User;
ngOnInit()
  {
    return this.dataService.createUser().subscribe(data=>this.user=data); 
  }

没有成功。但是用户是在我的服务器上以两种方式创建的。我看不懂一些基本知识,但在网上找不到任何好的解释。你能帮帮我吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-29 03:46:20

首先,确保您的api/服务按预期的方式工作,我的意思是,它实际上返回了前面所述的所需响应。这里还有我创建的示例代码

代码语言:javascript
复制
  constructor(private httpClient: HttpClient){}
  name = 'Angular';
  data: Data;
  getData(){
    return this.httpClient.get<Data>(`https://swapi.co/api/people/1/`);
  }
  ngOnInit(){
    this.getData().subscribe((res: Data)=>{this.data = res;})
  }

export interface Data{
  name: string;
  height: string;
}

<p>
  Name : {{data.name}} <br>
  Height: {{data.height}}
</p>

您可以看到这段代码在这里工作,斯塔克布利茨。希望这有帮助:)。如果你还面临问题请告诉我。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55410015

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档