Angular2(前面)和Yii2(结束) - 带有'Content-Type'选项的http.get:'application / json'

时间:2016-10-16 21:55:13

标签: json xml angular yii2

我一直试图将Angular2示例“Tour of Heroes”作为前端部分和Yii2框架作为后端连接 控制器在yii2

<?php
namespace app\controllers;
use yii\rest\ActiveController;
class HeroesController extends ActiveController
{

    public $modelClass = 'app\models\Heroes';

    public function behaviors()
    {

        return       
        yii\helpers\ArrayHelper::merge(parent::behaviors(), [
            'corsFilter' => [
                'class' => \yii\filters\Cors::className(),
            ],
        ]);
    }
}

结果(http://server.local/heroes):

<response>
<item>
<id>11</id>
<name>Mr. Nice</name>
<title>князь</title>
</item>
<item>
<id>12</id>
<name>Narco</name>
<title>граф</title>
</item>
<item>
<id>13</id>
<name>Bombasto</name>
<title>барон</title>
</item>

curl H'Content-Type':'application / json''http://server.local/heroes'工作正常,我得到JSON

但我不能在Angular2中收到这个。 http.get包含选项Content-Type':'application / json

export class HeroService {
  private headers = new Headers({'Content-Type': 'application/json'});
  private options = new RequestOptions({ headers: this.headers});
  private heroesUrl ='http://server.local/heroes';// 'app/heroes';  // URL     to web api
  constructor(private http: Http) { }
  getHeroes(): Promise<Hero[]> {
               return this.http.get(this.heroesUrl, this.options      
    )
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
  }

但我得到一个空的英雄[]

1 个答案:

答案 0 :(得分:1)

请阅读此Yii Response Formatting或在您的控制器中使用此功能

<div id="root">
    <input type="text" id="input" v-model="message"/>

    <p>The value of the input is : {{message}}</p>

    <ul>
        <li v-for="n in names" v-text="n"></li>
    </ul>

    <input id="input1" type="text"/>

    <button id="button"> Add More </button>
</div>

<script>
    var app = new Vue ({
        el : '#root',
        data : {
            message : 'Hello World!',
            favourite : 'author',
            names : ['Sunil' , 'Anis' , 'Satyajit']
        },
    });

    document.queryselector('#button').addEventListener('click', function(event) {
        var n = document.queryselector('#input1');
        app.names.push(n.value);
        n.value = '';
    });

</script>