AngularJS 2 TypeScript structure

My application includes a user service for managing user operations and an interface for the user object.

user.service.ts

import {Injectable} from 'angular2/core';

export interface User {
  name: string;
  email?: string;
  picture?: string;
}

@Injectable()
export class UserService {
  me: User;

  constructor() {

  }

  setUser(user: User) {
    this.me = user;
  }
}

When attempting to set the user in the login component using the profile returned from the login service, I encounter the following error:

Property 'firstName' does not exist on type '{}'.

login.component.ts

import {Component} from 'angular2/core';

import {User, UserService} from './services/user.service';
import {LinkedinService} from './services/linkedin.service';

declare const IN: any;

console.log('`Login` component loaded asynchronously');

@Component({
  selector: 'Login',
  providers: [
    UserService,
    LinkedinService
  ],
  template: require('./login.html')
})
export class LoginComponent {
  me: User;

  constructor(public linkedinService: LinkedinService, public userService: UserService) {
    this.me = userService.me;
  }

  ngOnInit() {
    console.log('hello `Login` component');
  }

  login() {
    this.linkedinService.login()
      .then(() => this.linkedinService.getMe()
      .then(profile => this.userService.setUser({ name: profile.firstName })));
  }
}

linkedin.service.ts

import {Injectable} from 'angular2/core';

declare const IN: any;

@Injectable()
export class LinkedinService {
  constructor() {
    IN.init({
      api_key: 'xxxxxxxxxxx',
      authorize: true
    });
  }

  login() {
    return new Promise((resolve, reject) => {
      IN.User.authorize(() => resolve());
    });
  }

  getMe() {
    return new Promise((resolve, reject) => {
      IN.API.Profile('me').result((profile) => resolve(profile.values[0]));
    });
  }
}

I am struggling with importing the User interface from UserService and utilizing it within the LoginComponent. Can anyone provide guidance on what I may be doing incorrectly? Should the User interface be used inside the LoginComponent?

Answer №1

Focusing on the specific code snippet:

  .then(() => this.linkedinService.getMe())
  .then(profile => this.userService.setUser({ name: profile.firstName })));

The type of profile is determined by the response from this.linkedinService.getMe(). It appears to be something like a Promise<{}>, lacking the firstName attribute, resulting in an error:

Property 'firstName' does not exist on type '{}'.

Solution

Review the code and signatures within the linkedinService. This issue is unrelated to the contents of the user.service.ts file being discussed 🌹

Revision

Focusing back on the code snippet:

 getMe() {
    return new Promise((resolve, reject) => {
      IN.API.Profile('me').result((profile) => resolve(profile.values[0]));
    });
  }

The returned value is dependent on what is passed to resolve. Ensure that profile.values[0] has the correct type. Alternatively, provide guidance to the compiler:

 getMe() {
    return new Promise<{firstName:string}>((resolve, reject) => {
      IN.API.Profile('me').result((profile) => resolve(profile.values[0]));
    });
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Options for Angular's routerLinkActiveDirective

I have a link that looks like this <li routerLinkActive="active" class="nav-item"> <a [routerLink]="['contracts']" [queryParams]="{ activeOnly: false }" class="nav-link">Contracts</a> </li> As you can see, in the param ...

Uploading images with Angular, Node.js, and MySQL

Is there a way to upload an image to a MySQL blob field using node.js, and then use Angular to display it as an image? I'm looking for suggestions on how to accomplish this. Any ideas? ...

The appearance of the Angular app undergoes a change following deployment using ng build

I have been working with Angular for several years now, but only recently delved into using Angular Material components in my latest project. I was pleased with how my layout turned out and ready to push it to production. However, after deployment, the com ...

The dynamic fusion of Typescript and Angular 2 creates a powerful

private nodes = []; constructor(private nodeService: NodeService) {} this.nodeService.fetchNodes('APIEndpoint') .subscribe((data) => { this.nodes.push(data); }); console.log(this.nodes) This ...

Lerna and Create React App (CRA) problem: When using the command "lerna run --parallel start", the devServer does not initiate

I am currently working on managing 2 projects within lerna packages. One project is a package, and the other is a CRA website. When I run "yarn start" for each package individually, I can see the build folder and the website being loaded on the development ...

Disallow negative numbers but allow decimals in HTML input

I need help restricting user input to prevent negative numbers while still allowing floating point numbers in my Angular project. Any suggestions using Angular tools would be greatly appreciated. Thanks! ...

Should loaders be utilized in an Angular application?

Webpack configuration allows the use of various loaders, such as file-loader, html-loader, css-loader, json-loader, raw-loader, style-loader, to-string-loader, url-loader, and awesome-typescript-loader. Does Angular have built-in knowledge of loaders with ...

Unable to showcase the content inside the input box

I am having trouble displaying a default value in an input field. Here is how I attempted to do it: <input matInput formControlName="name" value="Ray"> Unfortunately, the value is not appearing as expected. You can view my code o ...

npm run start is functioning correctly while ng serve is experiencing issues

I attempted to launch an angular 2 application with ng serve on my Linux machine, but encountered issues. However, using the npm run start command worked perfectly fine for me. Upon running ng serve, I received the following message: As a forewarning, we ...

How do I implement data range filtering in Typescript?

Seeking assistance with filtering data by date range and forwarding the results to the client. The objective is to extract tickets created within specific dates, but I keep encountering a console error which is proving challenging to resolve. var befor ...

Setting the response type to text in Angular 6 when making an http call

Attempting to send an HTTP request to the Spring REST API, which returns a string value ('success' or 'fail'). However, I am uncertain of how to specify the response type as a string value when making the call to the API. The error mess ...

First, download a npm package and integrate it into TSX files

Hello all, I am currently working on my very first project using React, Typescript, and ASP.NET Core. As a beginner in this technology stack, I seek your patience and understanding as I encounter challenges along the way. Right now, I'm facing an issu ...

NestJS does not recognize TypeORM .env configuration in production build

Currently, I am developing a NestJS application that interacts with a postgres database using TypeORM. During the development phase (npm run start:debug), everything functions perfectly. However, when I proceed to build the application with npm run build a ...

Is there a way to make sure that ngbpopovers stay open even when hovering over the popover content?

I have implemented a ngbpopover to display user information on an element. Currently, the popover is triggered on both hover and click events, but I would like it to remain open when hovered over, instead of closing as soon as the mouse moves away. How c ...

Issue with side panel not closing when clicked outside on IOS devices using Angular 6

On all devices except for IOS, the layout side panel is closing when clicking on the DOM: @ViewChild('closeContainer') LeftMenuObj; @HostListener('document:click', ['$event']) clickedOutside($event) { if (this.L ...

I need help with creating an AJAX JSON call using Angular. Let me share the JavaScript function that I currently have

When a button is clicked, the function below is called. It retrieves data from a JSON file and stores it if a success message is received. Here is a screenshot of the returned data. My JavaScript function is working correctly, but I am new to Angular and l ...

In a production environment, disable caching for server functions in Next.js

In my Next.js 14 project, I have a page that utilizes default Server-side Rendering (SSR) to fetch data and pass it to client components. export default async function Page() { const magazines = await getMagazines(true); return ( <Box sx= ...

Looking to dynamically adjust row color based on status using ANGULAR 4

In my table, I have 6 columns: name, email, phone, company, status_1, and status_2. Both status_1 and status_2 can have two options: "1" or "0." My Requirement: I want to change the color of the row based on the following logic: if(status_1 is "1" ...

Angular 2 cleaning up subscriptions when view is destroyed

I've developed an interesting "appService" that serves as the intermediary between all my components, handling interactions like forms and navigations. This service boasts multiple event emitters to which various components subscribe for different pu ...

When executing the "node app.js" command, the <app-root> element appears empty in the browser

After creating an Angular 7 application with the Angular CLI and adding my express server, I encountered a strange issue. When starting my app with the command "node server/app.js", the browser displayed <app-root></app-root> in the "Elements" ...