简体   繁体   English

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

[英]Angular constructor doesn't set a local variable before ngOnInit() is called

I am struggling with calling the backend from angular. 我正在努力从角度调用后端。 When I create a component I also get the parameter "category" from the URL like this: 当我创建一个组件时,我也从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();
      }
}

This works well, but now in the ProductsService, where I call the http.get I think it is not working fine. 这很好用,但现在在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}})
    }
}

Because when I try to log the req.body.category in the backend, it says it is null. 因为当我尝试在后端记录req.body.category时,它表示它为null。 But it is not, it is the right value. 但事实并非如此,这是正确的价值。

This is what I am trying to do in Node: 这就是我在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 阅读本文: Todd MoTTo:Angular构造函数与ngOnInit

Then move your constructor code into your ngOnInit method. 然后将构造函数代码移动到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. 然后在组件中侦听解析器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
      }
    });
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM