在调用ngOnInit()之前,Angular构造函数未设置局部变量

时间:2019-01-09 17:34:38

标签: javascript angular

我正在努力从角度调用后端。当我创建一个组件时,我还会从URL中获得参数“ category”,如下所示:

export class ProductsComponent{

    productList = []
    category = ""

    $params;
    $products;

    constructor(
        private products: ProductsService,
        private route: ActivatedRoute
    ){}

    ngOnInit() {
        this.$params = this.route.params.subscribe(params => {
        this.category = params['category']
        });

        this.$products = this.products.products(this.category).subscribe(
            productList => {
                this.productList = productList.result
            },
            err => {
                console.log(err)
            }
        )
    }

    ngOnDestroy(){
        // DON'T FORGET TO UNSUBSCRIBE!!!
        this.$params.unsubscribe();
        this.$products.unsubscribe();
      }
}

这很好用,但是现在在ProductsService中,我称之为http.get的地方,我认为它不能正常工作。

@Injectable()
export class ProductsService {
    constructor(private http: HttpClient, private router: Router) {}

    public products(category: string): Observable<any> {
        return this.http.get(`/products/getallproducts`, {headers: {'Content-Type': 'application/json'}, params: {'category': category}})
    }
}

因为当我尝试在后端登录req.body.category时,它说它为null。但这不是正确的值。

这是我要在Node中执行的操作:

products.get(('/getallproducts'), (req, res) => {
    let category = req.body.category;
    console.log("REQ" + req.body)

    if(category === "all") {
        ProductModel.findAll()
        .then(result => {
            res.json({result: result})
        })
        .catch(err => {
            res.json({error: err})
        })
    } else {
        ProductModel.findAll({
            where: {
                productsubcategory: category
            }
        })
        .then(result => {
            res.json({result: result})
        })
        .catch(err => {
            res.json({error: err})
        })
    }
})

1 个答案:

答案 0 :(得分:3)

  

查看本文:Todd MoTTo: Angular constructor versus ngOnInit

然后将您的构造函数代码移到您的 ngOnInit 方法中。

// Add these;
$params;
$products;

constructor(
  private products: ProductsService,
  private route: ActivatedRoute
){}

ngOnInit() {
  this.$params = this.route.params.subscribe(params => {
    this.category = params['category']
  });

  this.$products = this.products.products(this.category).subscribe(
    productList => {
      this.productList = productList.result
    },
    err => {
      console.log(err)
  });
}

ngOnDestroy(){
  // DON'T FORGET TO UNSUBSCRIBE!!!
  this.$params.unsubscribe();
  this.$products.unsubscribe();
}
  

更新:我知道你现在在做什么。对我来说似乎有点倒退。首先,您正在加载组件,然后去 GET 一些后端数据。如果要路由到需要某些数据的新设备,请尝试使用解析器。使用解析器,您可以获取有关路线更改的新数据。是否要暂停解析器直到获取数据(并在单击的链接上有一个微调器),还是显示一个加载屏幕并等待它,由您自己决定。但是,解析器将在加载路由时加载,并将发布结果。然后在组件中侦听解析器Observable。

// In Routes
{
  path: 'products/:category',
  component: YourComponent,
  resolve: {
    data: ProductsResolver
  }
},// rest of routes.

@Injectable()

export class ProductsResolver implements Resolve<any> {

constructor(
  private http: HttpClient
){}

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any>|Promise<any>|any {
  return this.http.get('/products/getallproducts',
    {
      headers: {
        'Content-Type': 'application/json'
      },
      params: {
        'category': route.params.category
      }
    });
}
  

然后该组件将是...

$products;

constructor(
  private route: ActivatedRoute
){}

ngOnInit() {
  this.$products = this.route.data.subscribe(productList => {
    this.productList = productList.result;
  },
  err => {
    console.log(err)
  });
}

ngOnDestroy(){
  this.$products.unsubscribe();
}