I've been following the Spring Security and Angular tutorial but angular
fails to compile after this step:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Demo';
greeting = {};
constructor(private http: HttpClient) {
http.get('resource').subscribe(data => this.greeting = data);
}
}
My IDE complains that id
and content
are unresolved variables
in
<div style="text-align:center"class="container">
<h1>
Welcome {{title}}!
</h1>
<div class="container">
<p>Id: <span>{{greeting.id}}</span></p>
<p>Message: <span>{{greeting.content}}!</span></p>
</div>
</div>
Is this tutorial just out of date or am I possible doing something wrong?
CodePudding user response:
You IDE is complaining because greetings
is an empty object. It's normal, because it is an empty object greeting = {};
.
If you want to avoid this warning, you can create an object with optionnals properties:
class Data {
constructor(public id?:string, public content?:string){}
}
and use it in your component greeting: Data = {};
You can also create an object without optionnals properties:
class Data {
constructor(public id:string, public content:string){}
}
and use it in your component greeting: Data;
and in your HTML use
<p>Id: <span>{{greeting?.id}}</span></p>
<p>Message: <span>{{greeting?.content}}!</span></p>
You can also use greeting: any;
but I would not recommand the use of any
if you can type your object instead. It's much clearer to use.
Or just ignore the warning/suppress the warning for the sake of the tutorial only.