2

I'm new to AngularJS 2 and this is my first time trying to compile it with TSlint. I did Tour of Heroes tutorial, and there is a part like the one below, which TSlint doesnt want to compile saying object access via string literals is disallowed.

ngOnInit(): void {
    this.route.params.forEach((params: Params) => {
      let id = +params['id'];
      this.projectService.getProject(id)
        .then(project => this.project = project);
    });
  }

I'm not sure if I understand the problem and I'm lost if it comes to solving it. Could you help me, please?

My other codes

    getProjects(): Promise<Project[]> {
      return this.http.get(`${this.configuration.Server}projects${this.configuration.ApiUrl}`)
                    .toPromise()
                    .then(response => response.json())
                    .catch(this.handleError);
  }

    getProject(ident: number): Promise<Project> {
      return this.getProjects()
             .then(projects => projects.find(project => project.id === id));
    }
Leukonoe
  • 649
  • 2
  • 10
  • 29

2 Answers2

7

I would just get rid of this rule. Accessing a property by string, is sometimes necessary. If you look in your tslint.json file you should see the property "no-string-literal". Just change that to false.

If you want to keep the rule, then for this particular case, you can just type to the params to have an id. You can do this because Params type is simply {[key: string]: any}

route.params.subscribe((params: {id: string}) =>{
  let id = +params.id;
})
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
0

It can be fixed by assign a string literal to a variable. And use it inside the [].refer this link, it has multiple options to resolve this issue.

Community
  • 1
  • 1
Devendiran Kumar
  • 223
  • 3
  • 12