Обмен данными между компонентами в Angular 7
Я хочу обмениваться данными между компонентами с помощью маршрутизации.
При попытке компиляции появляется следующая ошибка:
NewTasksComponent.html: 13 ОШИБКА TypeError: Невозможно прочитать свойство 'new_tasks' из неопределенного
Как я могу решить эту проблему?
get-data.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class GetDataService {
constructor(private http : HttpClient) { }
public shareddata : any;
get_data(){
this.http.get("https://raw.githubusercontent.com/MalishBob/WowworksTest1/master/works.json").subscribe((data) => {
this.shareddata = data;
});
}
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule, Routes} from '@angular/router';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NewTasksComponent } from './components/new-tasks/new-tasks.component';
const appRoutes: Routes = [
{path: 'newtasks', component:NewTasksComponent}
]
@NgModule({
declarations: [
AppComponent,
NewTasksComponent
],
imports: [
BrowserModule,
AppRoutingModule,
RouterModule.forRoot(appRoutes),
HttpClientModule
],
providers: [GetDataService],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
import { GetDataService } from './get-data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
constructor() { }
}
app.component.html
<div class="content">
<div class="wrapper wrap-menu">
<div class="add"></div>
<div class="menu">
<ul>
<li>
<a [routerLink]="['/newtasks']">
New
<span class="num_status">123</span>
</a>
</li>
<li>
.....
</li>
</ul>
</div>
<router-outlet></router-outlet>
</div>
new-tasks.component.ts
import { Component, OnInit } from '@angular/core';
import { GetDataService } from '../../get-data.service';
@Component({
selector: 'app-new-tasks',
templateUrl: './new-tasks.component.html',
styleUrls: ['./new-tasks.component.css']
})
export class NewTasksComponent implements OnInit{
constructor(private dataservice: GetDataService ) { }
works: any;
ngOnInit() {
this.works = this.dataservice.shareddata
}
}
new-tasks.component.html
<div class="wrapper wrap-table">
<table>
<thead>
<tr>
<th style="width: 10%;">ID</th>
<th style="width: 15%;">City</th>
<th style="width: 50%;">Name</th>
<th style="width: 15%;">Time</th>
<th style="width: 10%;">Amount</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let work of works.new_tasks">
<td>{{work.id}}</td>
<td>{{work.city}}</td>
<td>{{work.description}}</td>
<td>{{work.time_to}}</td>
<td>{{work.amount}}</td>
</tr>
</tbody>
</table>
</div>