【问题标题】:get call for angular2 failed to bind data获取对 angular2 的调用无法绑定数据
【发布时间】:2016-10-29 15:09:47
【问题描述】:

我正在尝试使用 http get 调用显示来自 db 的记录,但最后我无法做到这一点,我不确定错误在哪里,

我的组件:

import { Component} from '@angular/core';
import {Http, Response, Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Subject } from 'rxjs/Subject';
import {Control,FormBuilder,ControlGroup,Validators} from '@angular/common';
import { IDetails } from './pro';
import {GetAllList } from './service'

@Component({
    templateUrl: './components/professional/professional.html',
    providers :  [GetAllList]
})

export class Professional {
    details:IDetails[];

    constructor(private _service:GetAllList) { }

    click(){
        this._service.getList()
            .subscribe(details => this.details = details); 
    }
}

我的 HTTP 请求服务:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import { IDetails } from './pro';

@Injectable()
export class GetAllList {
    private _productUrl = 'http://localhost/angular/index.php/profile/getProfile';

    constructor(private _http: Http) { }

    getList(): Observable<IDetails[]> {
        return this._http.get(this._productUrl)
            .map((response: Response) => <IDetails[]> response.json())
            .do(data => console.log('All: ' +  JSON.stringify(data)));

    }
}

我的简单模板:

<button click = "click()" >v</button>{{details}}

【问题讨论】:

    标签: html angularjs angular


    【解决方案1】:

    要绑定到事件,您需要使用 (event)='expression' 语法,如下所示:

    <button (click)="click()" >v</button>
    <div *ngFor="let detail of details">
        <div>Firstname: {{detail.firstname}}</div>
        <div>Lastname: {{detail.lastname}}</div>
    </div>
    

    【讨论】:

    • 我还是不知道
    • 显示 MLHttpRequest 无法加载 localhost/angular/index.php/profile/getProfile。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'localhost:3000' 不允许访问。但在网络中显示 200 ok
    • 所以它确实告诉您,您需要在服务器响应中添加 Access-Control-Allow-Origin 标头 - 在此处阅读更多信息:restlet.com/blog/2015/12/15/understanding-and-using-cors
    • 另外,在 PHP 中添加 CORS 标头就像将 header("Access-Control-Allow-Origin: *"); 放在最顶部一样简单。
    • 哦,太好了,我明白了,非常感谢您的支持
    猜你喜欢
    • 2016-10-17
    • 2016-07-09
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 2011-01-19
    • 1970-01-01
    相关资源
    最近更新 更多