如何通过将localStorage值作为Angular4中的参数传递来调用API URL

时间:2018-05-28 08:47:46

标签: angular typescript

在我的应用程序中,我试图通过传递localStorage值作为参数来调用API。

产品组件:

 ngOnInit() {
    this.productCode = this.CartdataService.selectedProduct;

     this.myItem = localStorage.getItem('Item_Code');
     console.log("1st :" + this.myItem);

    if(this.myItem !=this.productCode){  
      this.myItem = this.CartdataService.selectedProduct;
      console.log("2nd :" + this.myItem);
    }

    this.CartdataService.get_Product_Details(this.myItem).subscribe(
      data => {
        console.log("3rd :" + this.myItem);
        console.log(data);
        let key = 'Item_Code';  
        localStorage.setItem(key,this.myItem); //setting localStorage value
      });
  }

这里我要做的是首先调用产品组件检查服务中的产品代码(将另一个组件传递给服务)。如果它可用,那么我需要检查它localStorage值,如果不同,则使用服务数据调用url(如果相同),然后使用localStorage数据调用url。

每次上次使用的产品代码都存储在localStorage中。

我尝试过类似上面代码的内容,但它没有用。 任何人都可以帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

//set your **localstorage** data using **JSON.stringify**

       var data=[{'test':'data'}];

      localStorage.setItem('Item_Code',JSON.stringify(data));

//than get localstorage like below using **JSON.parse**

 var localdata=JSON.parse(localStorage.getItem('Item_Code'));

答案 1 :(得分:-1)

我看不出你在哪里设置'Item_Code'。

这是第一次只是未定义。是否有任何其他功能在此ngInit之前设置localStorage。

此外,您也没有在订阅内的任何位置更改this.myItem。我的意思是,这不是从回应中获得的。

this.CartdataService.get_Product_Details(this.myItem).subscribe(
      data => {
        console.log("3rd :" + this.myItem);
        console.log(data);
        let key = 'Item_Code';  
        localStorage.setItem(key,this.myItem); //setting localStorage value
      });

在这里你只是记录this.myItem而不是分配像

这样的东西
this.myItem = data.myItem;

请澄清!