簡體   English   中英

如何修改Angular組件以從后端獲取信息?

[英]How can I modify Angular component to get information from backend?

我有ts文件,我想在組件內部創建POST方法。 不幸的是,我嘗試按以下所示的方法進行操作,但未取得積極結果。

this.http.post("http://localhost:8000/", JSON.stringify({ body: 'String' }), {headers:{'Content-Type': 'application/json'}})

更新

我對后端邏輯進行了一些修改,並且意識到不需要在POST方法中發送正文。 我可以在URL參數中發送數據。 我想發送GET請求並將接收到的數據分配給需要Isth[]類型的對象的object.sth 此時,我的代碼如下所示。 但是console.log("data: "+object.sth); 賦值后返回data: undefined

this.http.get("http://localhost:8000/path?sth=exampleurl", headers).map(res => res.json()).subscribe(data => this.data = data);
object.sth = this.data;
this.http.post(url, JSON.stringify(YOURSTRING), {headers:{'Content-Type': 'application/json'}})

它應要求工作。 (您的第一個問題)

我將使用更完整的語法來更新答案。 希望這可以使您正常運行。

import { Http }       from '@angular/http';
import { Component }          from '@angular/core';
import { Observable }     from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Component({
  selector: 'my-app',
  template: `<h1>Hello World</h1>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent {

    private headers: Headers;
    private options: RequestOptions;

    constructor(private http: Http) {
        this.headers = new Headers({ 'Content-Type': 'application/x-www-form-        urlencoded' });
        this.options = new RequestOptions({ headers: this.headers });
    }

    ngOnInit() {
        this.doPost().subscribe(response => {
            console.log(response);
        });
    }

    doPost() {
        return this.http.post("http://localhost:8000/sth", this.options).map(res => res.json());
    }
}

原文:我認為您缺少的是訂閱。 除非您訂閱可觀察對象,否則它們將不會執行。

this.http.post("http://localhost:8000/", JSON.stringify({ body: 'String' }), {headers:{'Content-Type': 'application/json'}}).subscribe(res=>console.log(res));

僅作記錄,通常最好將http調用放在服務中,而不是放在組件中。

在您的組件頂部

import { Headers, Http } from "@angular/http";

您的組件:

constructor(private http: Http) {} 

yourRequest() {
   let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded' })

  this.http.post(url, JSON.stringify(YOURSTRING), headers).subscribe(res=>console.log(res));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM