简体   繁体   中英

Angular2 - how to get a variable from typescript to my html dom

I've used AngularJS a lot in the past, but Angular2 is a whole new world for me.. and I've not quite gotten it down.

I have a home.ts and a home.html

Inside my home.ts I have this:

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  userData:any;

  constructor(
    public navCtrl: NavController,
    private storage: Storage,
    private database: AngularFireDatabase) {
      this.storage.get('user').then((result) => {
        this.userData = result;
      });

  }

I have a localstorage variable for the user, and I'm assigning it to userData ..

Inside my .html file, I have a span that I'd like to populate with info from the userData variable... I thought it would be as easy as doing this:

<span id="userName">{{userData.firstName}}</span>

but I just get a ton of errors Cannot read property 'firstName' of undefined ...

How can I get the userData variable into my html? Thanks!

You have to wait till the this.storage.get('user') is resolved, before your then is executed userData is undefined and you are trying to do userData.firstName which is giving the error Cannot read property 'firstName' of undefined..

You can do

<span *ngIf="userData" id="userName">{{userData.firstName}}</span>

So you wait for your promise to resolve sand then show that value on the screen.

What I typically do in this scenario is use the elvis operator in my binding. What that would look like for you is:

<span id="userName">{{userData?.firstName}}</span>

The problem is Angular is trying to render the value but since this step is occuring while your async request is still resolving, it tries to access the first name property on an undefined property - hence it throws the exception you are seeing.

Something else you could do (less preferred imo) is to set an initial value to userData. For example:

userData: any = {};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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