【发布时间】:2020-01-13 14:19:25
【问题描述】:
我有两个组件:一个包含添加文件的表单的父级,另一个显示添加的项目(文件)列表的子级。我想在添加一个项目表后更新我的项目表,但我订阅了但不在附加时检测到更改(抱歉我的英语不好),这是我的代码:
'this.dataSource = resp.files;'不再更新,第一次只更新一次。
已解决!
files.component.ts
export class FilesComponent implements OnInit {
dataSource;
columnsToDisplay = ['name', 'year', 'created_at', '_id'];
expandedElement: File | null;
constructor(
public _file: FileService
) {}
ngOnInit() {
this._file.$files.subscribe((resp: any) => {
this._file.getFiles(); //*******PARTIALLY SOLVED i call getFiles() inside but
// Now constantly call getFiles() :/
this.dataSource = resp.files;
});
}
}
add-file.component.ts
send() {
const newFile = {
name: this.name,
status: 'activo',
year: this.yearCtrl.value,
from_id: this.selectedFrom._id,
career_id: this.selectedCareer
};
this._file.newFile(newFile).subscribe( (resp: any) => {
// this._file.getFiles(); //*******Removed
console.log(resp);
}
}, err => {
console.log(err);
};
服务.ts
@Injectable({
providedIn: 'root'
})
export class FileService {
private headers;
public URL = URL;
private files = new BehaviorSubject<any>([]);
public $files = this.files.asObservable();
constructor(
private _http: HttpClient
) {
this.headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
// this.getFiles(); //*******Removed
}
getFiles(id: String = null) {
this._http.get(URL + '/file', { headers: this.headers }).subscribe( (resp: any) => {
return this.files.next(resp);
});
}
newFile( newFile: any) {
console.log(newFile);
return this._http.post(this.URL + '/file', newFile, { headers: this.headers }).subscribe( (resp: any) => {
this.getFiles();
});
}
}
我正在使用角度材料表,但我的 component.ts 没有读取服务变量中的更改。
【问题讨论】:
-
您没有调用任何 getFiles 或 newFile 方法,因此 $files 永远不会更新!
-
sry 在我的第二个组件中,现在我将更新
-
服务中是否需要Subject/Observable?我会首先尝试通过从服务中直接返回
get()和post()的结果来让这个应用程序正常工作。 -
我有 2 个单独的组件,一个带有要添加的表单,另一个用于显示文件表,我想在添加项目时更新表
-
您已将行为主体的初始值设置为 [ ] ,并且在 ngOnInit 中您尝试从 $files 可观察值发出的值访问文件( resp.files )。确保在服务的 getfiles 方法、数组或包含文件数组的对象中将预期值传递给行为主体。
标签: angular service rxjs observable subject