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

标签 javascript angular

我正在努力从 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 时,它说它为空。但它不是,它是正确的值。

这就是我在 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})
        })
    }
})

最佳答案

Review this article: 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();
}

Update: I see what you're doing now. It appears to be a bit backwards to me. First you are loading the component, then going to GET some backend data. If you are routing to something new that requires some data, then try a resolver. With a resolver, you can fetch new data on route change. It is up to you if you want to pause the resolver until you get data (and have a spinner on the link that was clicked), or show a loading screen and wait for it. But the resolver will load when the route is loaded and it will publish the result. Then listen for the resolver Observable in the component.

// 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
      }
    });
}

And the component then would be...

$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();
}

关于javascript - 在调用 ngOnInit() 之前,Angular 构造函数不会设置局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54115548/

相关文章:

javascript - ngFor 在可折叠菜单卡中显示单个元素

javascript - 如何使用 Jest 单元测试触发 transitionend

javascript - @Host装饰器如何在注入(inject)器树中工作

javascript - 在 Werkzeug 异常上设置标题

javascript - 跳转到图像 map 上的特定位置

angular - 什么时候使用 Angular 2 工厂函数?

css - 从 Bootstrap 应用 css 类时的 PrimeNG 日历错误

javascript - 无法在 node.js 中发送 Javascript 对象数组

javascript - React Native 推荐使用什么 IDE?

javascript - 如何在没有斜 Angular 外观的情况下显示方形 div