Angular2 - 在模型中使用路由器方法时遇到问题

时间:2016-12-16 06:40:18

标签: angular

我试图使用角度路由器在我的模型中触发一个方法,我已经从组件视图中分离了我的模型。这是我的组成部分:

// we also need the Input module
import { Component, OnInit, Input } from '@angular/core';

// Our model
import { ArchiveProduct } from './archive-product.model';

@Component({
  selector: 'app-archive-product',
  templateUrl: './archive-product.component.html',
  styleUrls: ['./archive-product.component.css']
})
export class ArchiveProductComponent implements OnInit {

  // input variables from archiveProduct and match them to the ArchiveProduct model
  @Input() archiveProduct: ArchiveProduct;

  selectPost(): any {
    this.archiveProduct.selectPost();
  }      
  ngOnInit() {
  }

}

这是我的模特:

// Exports a class of ArchiveProduct
import { Router } from '@angular/router';

export class ArchiveProduct {

  // declare our props
  title: string;
  id: number;
  slug: string;

  // constructor
  constructor(title: string, id: number, slug: string, private router: Router ) {
    this.title = title;
    this.id = id;
    this.slug = slug;
  }

  selectPost(slug) {
    this.router.navigate([this.slug]);
  }

}

目前我是'提供的参数与任何签名或目标不匹配'错误。我做错了什么?

3 个答案:

答案 0 :(得分:0)

您正在调用错误的函数名称,您正在调用selectPost中不存在的函数ArchiveProduct,它应该是selectProduct

不正确的

  selectPost(): any {
    this.archiveProduct.selectPost();
  }

正确

  selectPost(): any {
    this.archiveProduct.selectProduct();
  }

答案 1 :(得分:0)

1)ArchiveProduct中的selectPost代码是

  selectPost(slug) {
    this.router.navigate([this.slug]);
  }

所以它有输入参数。在TypeScript中,假定函数需要每个参数。 但是你在ArchiveProductComponent中调用它而没有像这样的参数:

  selectPost(): any {
    this.archiveProduct.selectPost();
  }   

2)请注意ArchiveProduct中的selectPost

  selectPost(slug) {
    this.router.navigate([this.slug]);
  }

this.slug传递给导航方法而不是参数slug

答案 2 :(得分:0)

嘿,我最终意识到的是我调用的selectPost方法是从ArchiveProductComponent类操作的。所以我所做的就是将selectPost方法移动到archive-product.component:

import { Component, OnInit, Input } from '@angular/core';

import { Router } from '@angular/router';

// Our model
import { ArchiveProduct } from './archive-product.model';

@Component({
  selector: 'app-archive-product',
  templateUrl: './archive-product.component.html',
  styleUrls: ['./archive-product.component.css']
})
export class ArchiveProductComponent implements OnInit {

  constructor(private router: Router) { }
  // input variables from archiveProduct and match them to the ArchiveProduct model
  @Input() archiveProduct: ArchiveProduct;

  ngOnInit() {
  }

  selectPost(slug) {
    let route = 'product/' + slug;
    this.router.navigate([route]);
  }

}