将页面标题从Laravel 5.5传递给Angular 4

时间:2018-03-22 14:17:11

标签: angularjs laravel

在我的laravel控制器中,我写道:

public function index()
    {
        $products = Product::all(); // get all products
        $products['page_title'] = 'Demo Products'; //  page title

        return response()->json($products);
    }

在Angular 4中,我为此写道:

constructor(private productService: ProductService, private title: Title) {  }
ngOnInit() {
    //console.log('data');

    this.productService.getProducts()
      .subscribe(data => {
        this.products = data;
        this.title.setTitle(data.page_title);
      },

在角色下的html我写了以下内容:

<article class="col-md-4"  *ngFor="let product of products">
<div class="font-weight-bold">{{product.product_name}}</div>
<p>{{product.description}}</p>
<p>{{product.rating}}</p>
</article>

在index.html中,我写了<title></title>

它显示如下控制台错误:

  

ProductComponent.html:7错误错误:尝试diff'[对象时出错   宾语]'。只允许数组和迭代

在邮递员中,我看到以下内容:

    "18": {
        "id": 19,
        "product_name": "Adam Walsh",
        "description": "Rabbit coming to look for her, and the small ones choked and had just upset the week before. 'Oh, I BEG your pardon!' cried Alice in a shrill, loud voice, and see after some executions I have to ask.",
        "rating": 0,
        "price": 59.2,
        "created_at": "2018-03-22 11:04:39",
        "updated_at": "2018-03-22 11:04:39"
    },
    "19": {
        "id": 20,
        "product_name": "Marilyne Kulas II",
        "description": "I want to stay in here any longer!' She waited for a minute or two sobs choked his voice. 'Same as if his heart would break. She pitied him deeply. 'What is it?' he said, turning to Alice an.",
        "rating": 5,
        "price": 13.5,
        "created_at": "2018-03-22 11:04:39",
        "updated_at": "2018-03-22 11:04:39"
    },
    "page_title": "Demo Products"
}

1 个答案:

答案 0 :(得分:1)

发送错误是因为* ngFor需要一个数组进行迭代。

分配$ products [&#39; page_title&#39;]好像$ products是一个关联数组是错误的。 $ products是Illuminate \ Database \ Eloquent \ Collection。当发送它作为json时,Laravel将其解析为索引数组。但我猜你通过分配&page 39&#39;这样。

在发送之前尝试print_r($产品),检查一下。

我宁愿做这样的事情:

return response()->json(['data' => $products, 'page_title' => 'Demo Products']);

并且有角度:

this.productService.getProducts()
  .subscribe(data => {
    this.products = data.data;
    this.title.setTitle(data.page_title);
  },