Thanks so much Zlatko, this was very helpful. Your suggestion regarding the
AsyncPipe was also incredibly helpful.
Rich
On Wednesday, October 25, 2017 at 8:35:27 AM UTC-6, Zlatko Đurić wrote:
>
> Well, two things. For one, the way you define your property, *stock*,
> it's undefined when the thing is initialized. So, before the *dataService*
> gets
> the data back, it's undefined in the template, so yuou have
> *undefined.symbol* - so that's what fails.
>
> You can any of these:
>
> [...snip...]
> template: `Closing price for {{ stock?.symbol }} is {{ stock ?
> stock.close : '0' }}, while the opening was {{ stock && stock.opening || ''
> }} and high <span *ngIf="stock">{{ stock.high }}</span>`
> [...snip...]
>
> To solve your problem, pick any example. To learn how to solve the problem
> in the future, try to explain what each of these does.
>
> For some values (not this one though), you can also use *`{{ obj | async
> }}` * - it's called AsyncPipe in Angular, read up on it.
>
> 2 more things:
> - you fetch stuff in your constructor. That's not a good pattern, some
> things may not work as expected. Instead, do all of this init logic by
> implementing OnInit interface. It's pretty simple actually:
> import { Component, OnInit} from '@angular/core'
> @Component({
> selector:'my-cmp',
> template: 'Hi there',
> })
> export class MyCmp implements OnInit {
> constructor(private dataService: DataService) {} // in constructor,
> you basically only inject all the dependencies.
>
> ngOnInit() {
> // This runs when the component is fully initialized. You can do all
> the logic-related stuff here. If you also want to access view (template),
> implement AfterViewInit instead.
> this.dataService.getStocks().subscribe(stock => this.stock = stock);
> }
>
>
> Another tiny issue is that you declared *stock* as an array, not a single
> object.
>
> class MyComponent {
> obj: any; // that's an object. And it's undefined.
> obj2: any = {}; // that's also an object, initialized to {};
> obj3: any[]; // that's an array. But if you test
> this.obj3.length, it's gonna break because your array is empty.
> obj4: any[] = []; // also an array, but it's initialized when the
> object gets created. It's set to [] (empty array)
> ...
> }
>
> Hope this helps.
>
>
--
You received this message because you are subscribed to the Google Groups
"Angular and AngularJS discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.