【问题标题】:service from Angular 4 and CodeIgniter 3来自 Angular 4 和 CodeIgniter 3 的服务
【发布时间】:2018-04-07 11:59:55
【问题描述】:

我对 Angular2/4 中的服务有疑问。 我不断得到

ERROR SyntaxError: Unexpected token ' in JSON at position 0.

这是我使用 CI 的后端。 这是我的控制器book.php

//get book from database
function list_book_get()
{
    //call method get_list_book() in model m_book
    $dataBook = $this->m_book->get_list_Book();

    //if dataBook exist
    if($dataBook != null) { 
        $output['status'] = true;
        $output['data'] = $dataBook;
    } else {    // if dataBook not exist
        $output['status'] = false;
        $output['message'] = "empty";
    }

    //send response
    $this->response(json_encode($output));
}

CI 中的模型:

function get_list_book() {  
        return $this->db->get('book')->result();
    }

这是我在 Angular 4 中的服务:

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

@Injectable()
export class BookService {

  constructor(private http: Http) {

  }

    books=[];
    getBooks(){
      return this.http.get("http://localhost/restserver/book/list_book.php")
      .map(res => res.json());
    } 


}

这是我来自 CI 的 json:

'{"status":true,"data":
[{"id":"1","title":"SAINS","author":"ERLANGGA","isbn":"089928778"},
{"id":"2","title":"Geography","author":"ERLANGGA","isbn":"089182372"},
{"id":"3","title":"Math","author":"Srilangka","isbn":"091283181"},
{"id":"4","title":"test","author":"test","isbn":"1283798127"},
{"id":"5","title":"AAAA","author":"BBB","isbn":"91092301290"},
{"id":"6","title":"BBB","author":"CCC","isbn":"01920192"}]}'

我假设我的 json 中的引号 (') 使我的应用程序出错。 如何删除那些引号?

【问题讨论】:

    标签: php json angular codeigniter


    【解决方案1】:

    从 CI Controller 发送 json 响应的正确方法是:

    function list_book_get()
    {
        ...
        return $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode($output));
    }
    

    你在单引号 bcoz (意思是字符串) 中得到 json,你 尚未定义内容类型。

    【讨论】:

    • 嘿,我能问你一些事情吗,现在我的前端(角度)给出了这个错误“错误错误:找不到类型为'object'的不同支持对象'[object Object]'。NgFor 仅支持绑定到诸如数组之类的可迭代对象。”你知道为什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    相关资源
    最近更新 更多