1

I've got this data from a HTTP Response

{
"files": [ ],
"posts": [
    {
        "content": "Dies ist ein Test-Posting, das zum Projekt 2 gehört.",
        "id": 2,
        "name": "Beispiel Post 2",
        "timestamp": "Wed, 10 Aug 2016 19:52:09 GMT"
    }
],
"project": {
    "id": 2,
    "info": "Dies ist der Text für das Beispiel Projekt 2",
    "name": "Beispiel Projekt 2",
    "timestamp": "Wed, 10 Aug 2016 19:50:59 GMT"
    }
}  

Its stored into a component variable and now I want to access it in my template. I tried to do something like this:

{{project.project.id}}  

It does not work. The object is stored like that:

Object { files: Array[0], posts: Array[1], project: Object }  

I already tried out solutions like this: iteration a json object on Ngfor in angular 2 but it wont help.

Heres the exception I got:
Uncaught (in promise): Error: Error in ./ProjectDetailComponent class ProjectDetailComponent - inline template:0:4 caused by: self.context.project is undefined

For more details, here are the files:

Component:

@Component({
    selector: 'app-project-detail',
    templateUrl: './project-detail.component.html',
    styleUrls: ['./project-detail.component.sass']
})
    export class ProjectDetailComponent implements OnInit {
    private project;
    private errorMessage;

    constructor(private route: ActivatedRoute,
                private router: Router,
                private projectService: ProjectsService) {
    }

    ngOnInit() {
        this.route.params.forEach((params: Params) => {
            let id = +params['id'];
            this.projectService.getProjects(id).subscribe(
                function (project) {
                    this.project = project;
                },
                error => this.errorMessage = <any>error
            );
        });
    }

}  

Service:

@Injectable()
export class ProjectsService {

    constructor(private http: Http) {}

    private projectsUrl = 'http://localhost:2000/api/projects/';

    getProjects(id?: number): Observable<any>{
        if(id){
            return this.http.get(this.projectsUrl + ""+id)
                .map(this.extractData)
                .catch(this.handleError);
        } else {
            return this.http.get(this.projectsUrl)
                .map(this.extractData)
                .catch(this.handleError);
        }


    }

    private extractData(res: Response) {
        let body = res.json();
        return body;
    }
    private handleError (error: any) {
        // In a real world app, we might use a remote logging infrastructure
        // We'd also dig deeper into the error to get a better message
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }
}

I appreciate any help!

Community
  • 1
  • 1

1 Answers1

0

The value is not assigned to where you thing it is.

ngOnInit() {
    this.route.params.forEach((params: Params) => {
        let id = +params['id'];
        this.projectService.getProjects(id).subscribe(

            // function (project) {
            // should be
            (project) => {             // <<<<=== change
                this.project = project;
            },
            error => this.errorMessage = <any>error
        );
    });
}

and use it with

{{project?.project?.id}}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • unfortunately no. I think the 'elvis' operator just checks wether a variable is defined or not. Correct me if i am wrong. –  Sep 18 '16 at 17:12
  • It checks if the expression left of `?.` is null before continuing evaluating the rest. Hard to tell whether this is the problem is your case without more details about what the problem is. – Günter Zöchbauer Sep 18 '16 at 17:25
  • I think the problem is simpler as it seems to be. I have the response stored as a object in a variable. Now I want to interpolate that variable in a template but it does not work. It wont show anything in the rendered template. –  Sep 18 '16 at 17:28
  • "Does not work" provides about as much information as "aölkjfaösldkjf öaslfdj " Do you get any error message in the browser console? – Günter Zöchbauer Sep 18 '16 at 17:28
  • You are right. But there were off course no erros cause I already used the elvis operator. I removed them and got this annoying exception: `Uncaught (in promise): Error: Error in ./ProjectDetailComponent class ProjectDetailComponent - inline template:0:4 caused by: self.context.project is undefined` –  Sep 18 '16 at 17:33
  • What do you get for `{{project | json}}`? – Günter Zöchbauer Sep 18 '16 at 17:37
  • If I go for `{{project | json}}` no error but also nothing rendered in the template (blank screen). `{{project.project.id | json}}` produced the same error as without | json. –  Sep 18 '16 at 17:41
  • Then the `project` variable just has no value. – Günter Zöchbauer Sep 18 '16 at 17:43
  • I console.log it right after i initialized it and its defnitley not empty nor has no value. –  Sep 18 '16 at 17:49
  • Then you don't assign it to `project`. Please post the code. – Günter Zöchbauer Sep 18 '16 at 17:49
  • It should be `{{project?.project?.id}}` – Günter Zöchbauer Sep 18 '16 at 18:06
  • You need `?.` because Angular first tries to render the view before the response from the server is available (`project` still `null`) – Günter Zöchbauer Sep 18 '16 at 18:15
  • yeah, i had to use ? –  Sep 18 '16 at 18:28